首页 > 代码库 > 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 区分不同的用户