简体   繁体   English

维护TCP连接

[英]Maintaining TCP Connection

I have a python program that reads in values from an ADC then writes them to a file as well as send them via TCP if a connection is available. 我有一个Python程序,该程序从ADC读取值,然后将它们写入文件,并在有连接的情况下通过TCP发送它们。 I can send the data fine however as data is constantly being read I would like to be able to keep the connection open. 我可以很好地发送数据,但是由于不断读取数据,我希望能够保持连接打开。 How do I get the client to check that the Server has more data to send and thus to keep the connection open? 如何让客户端检查服务器是否有更多数据要发送,从而保持连接打开?

This scenario seems very similar to one of our applications. 这种情况似乎与我们的一个应用程序非常相似。 We use ZeroMQ for this. 为此,我们使用ZeroMQ。

Using ZeromMQ with PUB/SUB 在PUB / SUB中使用ZeromMQ

On PyZMQ doc is example for using Pub/Sub. PyZMQ上,doc是使用发布/ 订阅的示例。

Data provider creates PUB socket and sends messages to it. 数据提供者创建PUB套接字并向其发送消息。

Data consumer sets up SUB socket and reads messages from. 数据使用者设置SUB套接字并从中读取消息。

Typically, PUB socket is fixed part of infrastructure, so it binds to some port, and SUB connects. 通常,PUB套接字是基础结构的固定部分,因此它绑定到某个端口,然后SUB连接。 But if you like, you can switch it and it works too. 但是,如果您愿意,可以对其进行切换,并且它也可以工作。

Advantages are: 优点是:

  • provider sends messages to PUB socket and does not block on it 提供程序将消息发送到PUB套接字并且不会对其进行阻止
  • reconnects are handled automatically 重新连接是自动处理的
  • if there is no consumer or connection, PUB socket silently drops the messages. 如果没有使用者或连接,则PUB套接字会静默删除消息。
  • the code to implement this is very short 实现这个的代码很短

Other messaging patterns with ZeroMQ ZeroMQ的其他消息传递模式

PUB/SUB is just one option, there are other combinations like PUSH/PULL, REQ/REP etc. PUB / SUB只是一种选择,还有其他组合,例如PUSH / PULL,REQ / REP等。

I have some services running for years with PUSH/PULL and it stays "quite well" (typically there are 6 weeks before there is a need to do some restart, but this is rather due to problems on hardware than in ZeroMQ library.) 我的PUSH / PULL服务已经运行了很多年,并且“保持良好”状态(通常需要6周的时间才能重新启动,但这是由于硬件问题而不是ZeroMQ库引起的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM