Created
March 22, 2018 14:26
-
-
Save ondras/250a19f4e074038013bd25524cf05c30 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env node | |
var WebSocketServer = require('websocket').server; | |
var http = require('http'); | |
var port = process.env.PORT || 8080; | |
var server = http.createServer(function(request, response) { | |
console.log((new Date()) + ' Received request for ' + request.url); | |
response.writeHead(404); | |
response.end(); | |
}); | |
server.listen(port, function() { | |
console.log((new Date()) + ' Server is listening on port', port); | |
}); | |
wsServer = new WebSocketServer({ | |
httpServer: server, | |
autoAcceptConnections: false | |
}); | |
var connections = []; | |
wsServer.on('request', function(request) { | |
var connection = request.accept(null, request.origin); | |
console.log((new Date()) + ' Connection accepted.'); | |
connections.push(connection); | |
connection.on('message', function(message) { | |
if (message.type === 'utf8') { | |
console.log('Received Message: ' + message.utf8Data); | |
connections.forEach(function(c) { c.sendUTF(message.utf8Data); }); | |
} | |
else if (message.type === 'binary') { | |
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); | |
connections.forEach(function(c) { c.sendBytes(message.binaryData); }); | |
} | |
}); | |
connection.on('close', function(reasonCode, description) { | |
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); | |
var index = connections.indexOf(connection); | |
connections.splice(index, 1); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment