Accessing DataSocket Server with Python
Chris Angelico
rosuav at gmail.com
Fri May 29 12:40:06 EDT 2015
On Sat, May 30, 2015 at 2:29 AM, Grant Edwards <invalid at invalid.invalid> wrote:
> If you assume TCP read/write operations are atomic and "message"
> boundaries are preserved, your code is wrong. It will eventually
> fail. Period.
Indeed. That said, though, if your writes are all smaller than one
packet, and you perfectly alternate a write and a read, a write and a
read, at both ends, then you can go a very long way without ever
running into this. In that case, you could have proper parsing and
buffering as a failure case, with the normal case expecting a
termination mark at the end of the socket-read - something like this:
write(query)
data = read(as_much_as_possible)
if data[-1] != "\n":
# Huh, stuff got split.
while True:
more_data = read(as_much_as_possible)
data += moredata
if data[-1] == "\n": break
cope_with_possibility_of(socket_disconnection)
handle_response(data)
Alternating writes and reads ensures that two messages can't be
combined, and if a single message fits inside a packet, it'll usually
be sent that way. But you still can't guarantee that.
ChrisA
More information about the Python-list
mailing list