Created
April 22, 2014 04:34
-
-
Save bengfarrell/11165435 to your computer and use it in GitHub Desktop.
Websocket implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var WebSocketServer = require('websocket').server; | |
var http = require('http'); | |
var server = http.createServer(function(request, response) { | |
console.log((new Date()) + ' Received request for ' + request.url); | |
response.writeHead(404); | |
response.end(); | |
}); | |
server.listen(9000, function() { | |
console.log((new Date()) + ' Server is listening on port 9000'); | |
}); | |
wsServer = new WebSocketServer({ | |
httpServer: server, | |
autoAcceptConnections: false | |
}); | |
function originIsAllowed(origin) { | |
return true; | |
} | |
wsServer.on('request', function(request) { | |
if (false) {//!originIsAllowed(request.origin)) { | |
// Make sure we only accept requests from an allowed origin | |
request.reject(); | |
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); | |
return; | |
} | |
var connection = request.accept();//'echo-protocol', request.origin); | |
console.log((new Date()) + ' Connection accepted.'); | |
connection.on('message', function(message) { | |
if (message.type === 'utf8') { | |
console.log('Received Message: ' + message.utf8Data); | |
connection.sendUTF(message.utf8Data); | |
} | |
else if (message.type === 'binary') { | |
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); | |
connection.sendBytes(message.binaryData); | |
} | |
}); | |
connection.on('close', function(reasonCode, description) { | |
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment