Here's a simple chat server for private / direct messages.
package.json
{ "name": "chat-server", "version": "0.0.1", "description": "WebSocket chat server", "dependencies": { "ws": "0.4.x" } }
server.js
var webSocketServer = new (require('ws')).Server({port: (process.env.PORT || 5000)}), webSockets = {} // userID: webSocket // CONNECT /:userID // wscat -c ws://localhost:5000/1 webSocketServer.on('connection', function (webSocket) { var userID = parseInt(webSocket.upgradeReq.url.substr(1), 10) webSockets[userID] = webSocket console.log('connected: ' + userID + ' in ' + Object.getOwnPropertyNames(webSockets)) // Forward Message // // Receive Example // [toUserID, text] [2, "Hello, World!"] // // Send Example // [fromUserID, text] [1, "Hello, World!"] webSocket.on('message', function(message) { console.log('received from ' + userID + ': ' + message) var messageArray = JSON.parse(message) var toUserWebSocket = webSockets[messageArray[0]] if (toUserWebSocket) { console.log('sent to ' + messageArray[0] + ': ' + JSON.stringify(messageArray)) messageArray[0] = userID toUserWebSocket.send(JSON.stringify(messageArray)) } }) webSocket.on('close', function () { delete webSockets[userID] console.log('deleted: ' + userID) }) })
instructions
To verify this, run npm install to install ws . Then, to start the chat server, run node server.js (or npm start ) on one tab "Terminal". Then on another tab “Terminal” run wscat -c ws://localhost:5000/1 , where 1 is the user ID of the connecting user. Then, in the third tab “Terminal”, run wscat -c ws://localhost:5000/2 , and then to send a message from user 2 to 1 , enter ["1", "Hello, World!"] .
Omissions
This chat server is very simple.
ma11hew28 Oct 19 '13 at 18:05 2013-10-19 18:05
source share