Python sockets: make sure TCP packets are sent before closing the connection

I work with a relay that is controlled via TCP. As I understand it, the following code should 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 closes before the packet actually sends, and the relay does nothing. As a dirty solution, I now put the sleep operator before closing the connection, and it works correctly.

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

Can I do something smarter to make sure the packet is actually sent before the connection is closed?

+4
source share
1 answer

SO_LINGER s.setsockopt. linger () . - :

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)
+2

Source: https://habr.com/ru/post/1502797/


All Articles