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.

    评论

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?