简体   繁体   English

使用套接字进行以太网通信的最佳实践

[英]Best practice for ethernet communication using socket

I have a fairly general question about best practice when using socket to communicate with remote hardware: should the socket be closed after each message is sent or left open? 当使用套接字与远程硬件通信时,我有一个关于最佳实践的相当普遍的问题:在每个消息发送或保持打开后是否应该关闭套接字?

To illustrate this question: I'm using python (and socket) to interface with a remote piece of hardware. 为了说明这个问题:我正在使用python(和socket)与远程硬件接口。 Typically, I'll send a command to the device every 30 seconds or so, receive the reply and then wait ~ 30 seconds. 通常,我会每隔30秒左右向设备发送一个命令,接收回复然后等待~30秒。

At present I'm doing: 目前我在做:

    # Open socket
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.sock.settimeout(10)
    self.sock.connect((self.host_ip_address, self.port))

    # Send Message
    self.sock.send(my_command)

    # Receive Reply
    data = self.sock.recv(1024)

    # Close socket
    self.sock.shutdown(socket.SHUT_RDWR)
    self.sock.close()

I wonder if this advisable, or should I simply leave the socket open for the duration of my session with the device (say ~ 1hr). 我想知道这是否可行,或者我应该在设备会话期间(例如~1小时)简单地打开插座。 Would this be robust? 这会很健壮吗?

Any tips / pointers welcomed thanks! 任何提示/指示欢迎致谢!

This is robust as long as you exchange data from time to time over your socket. 只要您通过套接字不时交换数据,这就很健壮。 If not, a Firewall/NAT can decide that the TCP connection is broken and stop routing the TCP packet. 如果不是,则防火墙/ NAT可以确定TCP连接已断开并停止路由TCP数据包。

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

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