2016-09-11 16:51
浏览 31


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!

图片转代码服务由CSDN问答提供 功能建议

我是新手,尝试通过替换Node.js服务器来学习它。 我的nodejs服务器具有以下组件:

  1. 它从客户端接收到Websocket消息。 客户端将为消息提供唯一的ID和密钥。 服务器将基于密钥来处理消息(就像REST接口一样),并使用唯一ID将消息返回给客户端,以便客户端知道服务器正在响应哪个消息。

  2. 对于某些消息,服务器将产生一个外部进程(每个连接一个)。 然后,服务器将充当生成的进程的“客户端”,发送具有唯一ID的JSON消息并接收返回的数据。 在这种情况下,服务器充当生成的进程和客户端之间的中介。

    在节点上,使它能够正常工作是微不足道的。 我只是将生成的进程添加到“主”中的连接中,并在主中使用了回调。 Websocket服务器模块和管理生成的过程通信的模块没有直接的交互,并且是完全通用的。

    但是,尽管我有一个可以正常运行的websocket程序包和一个spawn程序包,但我仍无法找到一个一般的方法来为每个websocket连接创建一个生成的进程 。 我曾考虑过传递回调和init,但是这种方法似乎有点黑。 我认识到该节点并在编程中可能需要不同的策略,但我想不出一种好的“执行”方法。 我欢迎任何建议!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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.
    解决 无用
    打赏 举报

相关推荐 更多相似问题