4

I am working with a relay that is controlled via TCP. As far as I understood the following code is supposed to work:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.0.200', 17494))
s.send(chr(101))
s.close()

However, I noticed that the socket gets closed before the package is actually send, and the relay does not do anything. As dirty solution I now put a sleep statement before closing the connection and it works properly.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.0.200', 17494))
s.send(chr(101))
time.sleep(0.01)
s.close()

Is there something more clever one can do to ensure that the package got actually send before closing the connection?

P.R.
  • 3,785
  • 1
  • 27
  • 47

1 Answers1

2

You could set the SO_LINGER option using s.setsockopt. The linger option makes the socket wait (internally) and close only after sending all the pending data upto the specified timeout value. Something like:

linger_enabled = 1
linger_time = 10 #This is in seconds.
linger_struct = struct.pack('ii', linger_enabled, linger_time)
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, linger_struct)
Manoj Pandey
  • 4,528
  • 1
  • 17
  • 18