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

是否为每个客户端执行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.

    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧