首页 > 代码库 > Node.js Websocket 区分不同的用户
Node.js Websocket 区分不同的用户
实现ws://serverIP:port/:param1/:param2 。通过param1,param2来管理不同的ws回话,以便实现群发和指定用户的消息推送
npm install ws --save node server.js
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) { console.dir(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) }) })
源自:http://stackoverflow.com/questions/16280747/sending-message-to-a-specific-connected-users-using-websocket
Node.js Websocket 区分不同的用户
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。