Created
August 19, 2019 19:23
-
-
Save SREENATHPGS/7e4f86dc0ae10bfde7f92569416f6324 to your computer and use it in GitHub Desktop.
This file contains hidden or 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(5050, function() { | |
console.log((new Date()) + ' Server is listening on port 5050'); | |
}); | |
wsServer = new WebSocketServer({ | |
httpServer: server, | |
autoAcceptConnections: false | |
}); | |
function originIsAllowed(origin) { | |
// put logic here to detect whether the specified origin is allowed. | |
return true; | |
} | |
//create an array to hold your connections | |
var connections = []; | |
var conMap = {}; | |
wsServer.on('request', function(request) { | |
console.log(request.url); | |
console.log(request); | |
console.log(request.origin); | |
if (!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); | |
var randNumber = Math.round(Math.random() * 0xFFFFFF); | |
//store new connection in map | |
conMap[randNumber] = connection; | |
console.log(conMap); | |
//store the new connection in your array of connections | |
connections.push(connection); | |
console.log((new Date()) + ' Connection accepted. Client ID: '+randNumber); | |
connection.sendUTF('your id is'+randNumber); | |
connection.on('message', function(message) { | |
if (message.type === 'utf8') { | |
recutf8data = message.utf8Data; | |
jsonifiedData = JSON.parse(recutf8data); | |
console.log(jsonifiedData); | |
console.log('Received Message: ' + message.utf8Data); | |
connectionId = conMap[parseInt(jsonifiedData["to"])]; | |
console.log(connectionId); | |
connectionId.sendUTF(jsonifiedData["message"]); | |
} | |
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