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?

3
  • This is pretty awkward. Calling close(2) on a socket should still send the data that's queued. Commented Sep 18, 2013 at 11:55
  • How do you check if the data is sent or not? Commented Sep 18, 2013 at 13:56
  • I see if the relay does something or not. Commented Sep 18, 2013 at 17:04

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.