简体   繁体   中英

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. Typically, I'll send a command to the device every 30 seconds or so, receive the reply and then wait ~ 30 seconds.

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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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