-
Notifications
You must be signed in to change notification settings - Fork 0
/
websockets.js
61 lines (43 loc) · 1.42 KB
/
websockets.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
56
57
58
59
var http = require('http');
var server;
server = http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
});
var WebSocketServer = require('websocket').server;
server.listen(3001, function() {
console.log((new Date()) + ' Server is listening on port 3001');
});
wsServer = new WebSocketServer({
httpServer: server
});
var count = 0;
var clients = {};
var map = {};
wsServer.on('request', function(r){
var connection = r.accept('echo-protocol', r.origin);
var id = count++;
clients[id] = connection;
console.log((new Date()) + ' Connection accepted [' + id + ']');
connection.on('message', function(message) {
console.log(message);
// The string message that was sent to us
var msgString = message.utf8Data;
// Loop through all clients
for(var i in clients){
// Send a message to the client with the message
clients[i].sendUTF("Server's response");
if (clients[i] == this){
map[i] = {
client: clients[i],
message: message
}
}
}
});
connection.on('close', function(reasonCode, description) {
delete clients[id];
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});