Socket in python and socket.recv()

345 views Asked by At

I am sending some request from the server to my client but I have some problem.

When I'm sending messages to the client, if I send many messages, I'll receive all with socket.recv()

Is there a way to get the messages one by one ?

Thanks

3

There are 3 answers

0
Martin James On

No. TCP is a byte stream. There are no messages larger than one byte.

5
Steffen Ullrich On

I assume that you are using TCP. TCP is a streaming protocol, not a datagram protocol. This means that the data are not a series of messages, but instead a single data stream without any message boundaries. If you need something like this either switch the protocol (UDP is datagram, but has other problems) or make your own protocol on top of TCP which knows about messages. Typical message based protocols on top of TCP either use some message delimiter (often newline) or prefix each message with its size.

0
deets On

You need to use some kind of protocol over otherwise bare sockets.

See python twisted or use something like nanomsg or ZeroMQ if you want a simple drop-in replacement which is message-oriented.

It is not transport-agnostic though, meaning they will only work if they are used on both ends.