4

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!

IanRoberts
  • 2,846
  • 5
  • 26
  • 33

1 Answers1

2

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.

Antoine
  • 1,070
  • 7
  • 11
  • Thank for the reply - do you mean leaving the socket open is robust, or closing and reoppening between communications is robust? – IanRoberts Dec 11 '15 at 10:50
  • leaving the socket open is robust as long you use it every X seconds (let say X < 60 second, but this is empiric as it will depend on third parties implementations ) . But the other approach is in general more robust, but will cost some time. If you don't target performance, I would go for closing and reopening. Be sure to really close it then and not to leave the connexion "floating". – Antoine Dec 11 '15 at 11:06
  • Also if you use open connection, it is a good idea to set the "keep alive" flag when opening the socket. See http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html and https://delog.wordpress.com/2013/08/16/handling-tcp-keepalive/ – Antoine Dec 11 '15 at 11:09
  • Thanks. To clarify, how do I "really close it and not leave floating". I thought self.sock.shutdown(socket.SHUT_RDWR) and then self.sock.close() would do that. Is there more I should do? – IanRoberts Dec 11 '15 at 12:10
  • Yes, it will do it. I was thinking about your program flow. Just make sure you do this call in all cases, if you socket is not local. – Antoine Dec 11 '15 at 12:45