1 var WebSocketServer = require('websocket').server;
2 var http = require('http');
3
4 var server = http.createServer(function(request, response) {
5 console.log((new Date()) + ' Received request for ' + request.url);
6 response.writeHead(404);
7 response.end();
8 });
9 server.listen(8080, function() {
10 console.log((new Date()) + ' Server is listening on port 8080');
11 });
12
13 wsServer = new WebSocketServer({
14 httpServer: server,
15 // You should not use autoAcceptConnections for production
16 // applications, as it defeats all standard cross-origin protection
17 // facilities built into the protocol and the browser. You should
18 // *always* verify the connection's origin and decide whether or not
19 // to accept it.
20 autoAcceptConnections: false
21 });
22
23 function originIsAllowed(origin) {
24 // put logic here to detect whether the specified origin is allowed.
25 return true;
26 }
27
28 wsServer.on('request', function(request) {
29 if (!originIsAllowed(request.origin)) {
30 // Make sure we only accept requests from an allowed origin
31 request.reject();
32 console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
33 return;
34 }
35
36 var connection = request.accept('echo-protocol', request.origin);
37 console.log((new Date()) + ' Connection accepted.');
38 connection.on('message', function(message) {
39 if (message.type === 'utf8') {
40 console.log('Received Message: ' + message.utf8Data);
41 connection.sendUTF(message.utf8Data);
42 }
43 else if (message.type === 'binary') {
44 console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
45 connection.sendBytes(message.binaryData);
46 }
47 });
48 connection.on('close', function(reasonCode, description) {
49 console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
50 });
51 });