Python sockets: how to only receive one message at a time

python, select, sockets

Solution

This is a perfectly normal behavior of a stream socket which is a stream of successive bytes, not a stream of messages. You may envisage to format your message by encoding for instance the len of the message followed by the message data. Then you can parse the received buffer with these indications. You can also wait until you find the corresponding ')' to the opening '('.

Problem

Just trying to understand how sockets work. I'm using a modified test select server and client I found. Here's the server: ``` import socket host = '' port = 50000 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) while 1: client, address = s.accept() running = 1 while running: data = client.recv(size) print("received: "+data + "\n") if data: client.send(data) running = 0 else: running = 0 client.close() ``` And the client: ``` import socket import sys host = 'localhost' port = 50000 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) sys.stdout.write('%') s.send("(Message1)") while 1: s.send("(Message2)") data = s.recv(size) sys.stdout.write(data) sys.stdout.write('%') s.close() ``` I'm expecting the server to print something like: ``` received: (Message1) received: (Message2) ``` since they're different messages sent separately, but instead I get: ``` received: (Message1)(Message2) ``` Is this related to the size of the data received, some kind of buffer thing, or is it timeout-related, or something else?

Original source