duanbei1709 2015-10-28 16:45
浏览 1069

是否为每个客户端执行1个唯一的Websocket连接?

I have a webpage that establishes a websocket connection with the server. I have to make sure that a user of the site can only establish a single connection, so opening a new tab and navigating to the same page will close the previous connection.

I was thinking of maintaining a map with the session id as the key; however, as the map would have to be constantly adjusted in size as more and more clients connect I am afraid of it having performance problems, and since it's accessed concurrently you would probably have to do some kind of locking.

Any ideas for performance efficient ways of ensuring a unique connection per client? Would love to hear suggestions, thank you.

  • 写回答

1条回答 默认 最新

  • donglu4159 2015-10-28 18:43
    关注

    I wouldn't be concerned about the performance of the solution outlined in the question. If you want to close the previous connection, there's no way around maintaining server side maps. Assuming a single server and that you are using the Gorilla websocket package, the following code should do the trick:

    var (
       mu sync.Mutex
       conns map[string]*websocket.Conn
    )
    
    func addConn(sessionID string, conn *websocket.Conn) {
       mu.Lock()
       prev := conns[sessionID]
       conns[sessionID] = conn
       mu.Unlock()
       if prev != nil {
          // Close will stop concurrent reads and writes.
          prev.Close()
       }
    }
    
    func removeConn(sessionID string, conn *websocket.Conn) {
       mu.Lock()
       // We don't simply delete(conns, session) to avoid race on cleanup.
       if conns[sessionID] == conn {
          delete(conns, sessionID)
       }
       mu.Unlock()
    }
    

    The cost of updating this map is small compared to the cost of accepting an incoming network connection, completing websocket handshake and everything else that's happening in scenario.

    评论

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗