Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you flush Python sockets?

I've written a server in Python that is meant to send data to the client in the form "Header:Message"

I would like to be able to have each message sent individually so that the client will need to perform minimal work in order to read the "header" and the "message"

Unfortunately, I can't figure out how to properly flush a python socket so when I have multiple sends execute in quick succession the messages get lumped together in the socket buffer and sent as one big chunk.

Example:

Server sends...

socket.send ("header1:message1")
socket.send ("header2:message2")
socket.send ("header3:message3")

Client receives... "header1:message1header2:message2header3:message3"

I'd like to receive three individual messages

header1:message1
header2:message2
header3:message3

I need a way to flush after each send

like image 576
Jah Avatar asked Oct 31 '09 20:10

Jah


People also ask

Can you flush a socket?

Flushing out the socket.Flushing out the socket can remove any food particles or other debris that may contribute to pain or possible infection.

How do you clear a socket?

Flushing the Socket Pools To flush the socket pools, go to chrome://net-internals/#sockets and click Flush socket pools. If you are already on the DNS page, just select Sockets in the left hand column. Usually you don't need to worry about flushing the socket pools.

How do I shutdown a server socket in Python?

You need to call shutdown() first and then close(), and shutdown takes an argument.

Do you have to close a socket in Python?

There's no need to call s.close() : with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: pass # Use the socket object without calling s.close(). The arguments passed to socket() are constants used to specify the address family and socket type. AF_INET is the Internet address family for IPv4.


1 Answers

I guess you are talking over a TCP connection.

Your approach is flawed. A TCP stream is defined as a stream of bytes. You always have to use some sort of separator and may not rely on the network stack to separate your messages.

If you really need datagram based services switch to UDP. You'll need to handle retransmission yourself in that case.

To clarify:

Flushing the send buffer usually creates new packages, just as you expect. If your client reads these packages fast enough you may get one message per read.

Now imagine you communicate over a satellite link. Because of high bandwidth and latency, the last router before the sat waits a short time until enough data is in the buffer and sends all your packets at once. Your client will now receive all packets without delay and will put all the data in the receive buffer at once. So your separation is gone again.

like image 91
ebo Avatar answered Oct 01 '22 11:10

ebo