The answer by Larry Hastings has some great general advice about sockets, but there are a couple of mistakes as it pertains to how the recv(bufsize)
method works in the Python socket module.
So, to clarify, since this may be confusing to others looking to this for help:
- The bufsize param for the
recv(bufsize)
method is not optional. You'll get an error if you call recv()
(without the param).
- The bufferlen in
recv(bufsize)
is a maximum size. The recv will happily return fewer bytes if there are fewer available.
See the documentation for details.
Now, if you're receiving data from a client and want to know when you've received all of the data, you're probably going to have to add it to your protocol -- as Larry suggests. See this recipe for strategies for determining end of message.
As that recipe points out, for some protocols, the client will simply disconnect when it's done sending data. In those cases, your while True
loop should work fine. If the client does not disconnect, you'll need to figure out some way to signal your content length, delimit your messages, or implement a timeout.
I'd be happy to try to help further if you could post your exact client code and a description of your test protocol.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…