-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
55 lines (45 loc) · 1.14 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const websocket = require('ws');
const hapi = require('hapi');
const server = new hapi.Server();
server.register(require('inert'), function() {});
server.connection({ port: process.env.PORT || 3000 });
server.route({
method: 'GET',
path: '/',
handler: (req, reply) => {
reply.file('index.html');
},
});
server.start(() => {
console.log('started');
});
const ws = new websocket.Server({ server: server.listener });
ws.broadcast = data => {
console.log('bc');
ws.clients.forEach(client => {
if (client.readyState === websocket.OPEN) {
client.send(data);
}
});
};
ws.on('connection', socket => {
console.log(socket);
ws.clients.forEach(client => {
if (client !== socket && client.readyState === websocket.OPEN) {
client.send('Client connection opened');
}
});
socket.on('message', data => {
console.log('data>>', data);
ws.clients.forEach(client => {
if (client !== socket && client.readyState === websocket.OPEN) {
client.send(data);
}
});
});
socket.on('close', () => {
ws.clients.forEach(client => {
client.send('Client connection closed');
});
});
});