• 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

  • 相关阅读:
    [CQOI2006]凸多边形
    NOIP后省选集训前文化课划水记
    FFT字符串匹配
    ghj1222的代码规范
    博弈论
    P1350 车的放置
    P2110 欢总喊楼记
    虫食算
    3192: [JLOI2013]删除物品
    逛公园
  • 原文地址:https://www.cnblogs.com/mataszhang/p/6676180.html
Copyright © 2020-2023  润新知