14

我面临以下问题:

我有一个客户端(最终是 n 个客户端)并且喜欢连接到服务器。客户端知道服务器/主机地址,但服务器不知道客户端的地址。我希望能够在客户端-服务器之间完成以下消息模式(客户端和服务器都需要能够完成以下消息模式):

  • 发布消息(预期没有回复)
  • 接收消息(预期没有回复)
  • 请求/接收消息(预期回复)
  • 流式消息(这可能是多余的,因为它可以通过上面的发布消息模式提供)

同样重要的一点,我挣扎的地方是如何连接到主机,同时仍然能够发送和接收消息。主机没有连接客户端的能力,它只能接受客户端的连接请求。请注意,我不寻找客户端和服务器都连接的代理/代理解决方案,否则我可以直接使用rabbitmq等解决方案。

我怎样才能最好地做到这一点,甚至更好地参考代码示例。

非常感谢。

4

1 回答 1

14

For connecting to the server, you need a DEALER socket on the client side, and a ROUTER socket on the server. Because you need a publish subscribe pattern you will need a SUB socket on the client side, and a PUB socket on the server side.

  Client       Server
+-------+      +--------+
| Dealer| <--> | Router |
|  Sub  | <--  |  Pub   |
+-------+      +--------+

So you bind the Router and the Pub sockets, and connect the Dealer, and the Sub sockets. Than when you want to:

  • Publish Messages (no reply expected): Create an envelope ( pub, channel, message ) and send it through the Dealer, on the Router side the router will receive the following envelope ( dealer, pub, channel, message ), so you can publish the message on channel through PUB socket.

  • Receive Messages (no reply expected): It's done with the SUB sockets on the client side, and since every publication goes through the ROUTER you can easily implement a subscription mechanism, or just add a SUB socket on the server side, and connect (inproc) to the PUB socket (maybe this is a cleaner solution).

  • Request / Receive Messages (reply expected): It can be done with the Dealer - Router. you just create a different envelope ( req, message ), so your Router ( receive: dealer, req, message ) will know that it should be processed, and can send a reply to the dealer. If your server needs to send requests to the clients, you just need to keep track of the connected clients, and send an envelope (dealer, req, msg), so your dealer can reply with example a ( rep, message ) envelope.

  • Streaming: as you stated it can be done with the publish pattern

This is how I would do it, if you need heart beating, it gets a bit complicated, but not much.

于 2013-06-10T08:47:45.027 回答