dpqaaczn141761 2016-09-11 16:51
浏览 39
已采纳

在Golang中处理WebSocket通信的设计实践

I am new to go and trying to learn it by replacing a nodejs server. My nodejs server had the following components:

  1. It received a websocket message from a client. The client would provide a unique ID and a key for the message. The server would process the message based on the key (much like a REST interface would) and return a message to the client with the unique ID so that the client would know which message the server was responding to.

  2. For some of the messages, the server would spawn an external process (one for each connection). The server would then act as a "client" to the spawned process, sending JSON messages with unique IDs and receiving back data. The server in this instance acts as an intermediary between the spawned process and the client.

On node it was trivial to get this to work generically. I simply added the spawned process to the connection in my "main" and used callbacks in the main. The websocket server module and the module governing the spawned process communication had no direct interaction and were completely generic.

However, while I have a websocket package and a spawn package that work well in go, I haven't been able to figure out a good way to generically create a spawned process per websocket connection. I've thought of passing callbacks and inits but this method seems hackish. I recognize that node and go probably require different strategies in programming but I can't think of a good "go" way of doing this. I welcome any suggestions!

  • 写回答

1条回答 默认 最新

  • dongyinpan9284 2016-09-12 00:38
    关注
    1. You describe how http protocol works, means request-response. If that all you need you may feel good with just keep-alive connections. Websocket is async in nature, messages aren't assume responses. Use-case is server-send-events for example.
    2. In Go server uses fire-and-forget strategy. It accepts connection, spawns goroutine to handle it, forgets it and listens for a new. Spawned goroutine upgrades connection to websocket and then serves client itself without any intermediary.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置