[ACCEPTED]-How do you flush Python sockets?-flush

Accepted answer
Score: 24

I guess you are talking over a TCP connection.

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

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

To clarify:

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

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

Score: 1

What you are trying to do, is split your 24 data into "batches".

For example, you are 23 operating on "batches" whenever you read 22 "lines" off a file. What defines a "line"? It's 21 a sequence of bytes terminated by '\n'. Another 20 example is: you read 64KiB "chunks" off 19 a file. What defines a "chunk"? You do, since 18 you read 65536 bytes every time. You want 17 a variable length "chunk"? You just prefix 16 your "chunk" with its size, then read the 15 "chunk". "aiff" files (whose implementations 14 are also the .wav and .avi files of MS Windows) and 13 "mov" files are organized like that.

These 12 three methods are the most fundamental methods 11 to organize a stream of bytes, whatever 10 the medium:

  1. record separators
  2. fixed size records
  3. records prefixed with their size.

They can be mixed and/or modified. For 9 example, you could have "variable record 8 separators", like an XML reader: read bytes 7 from first '<' until first '>', add 6 a slash after first '<' and call it end-of-record, read 5 stream until end-of-record. That's just 4 a crude description.

Choose a method, and 3 implement it in both the writer and reader. If 2 you also document your choices, you've just 1 defined your first protocol.

Score: 0

just append \n after every message... like 1

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

More Related questions