Reputation: 2956
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!
Upvotes: 4
Views: 1129
Reputation: 1070
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.
Upvotes: 2