python - Why only 1024 bytes are read in socketserver example -


i reading through documentation examples python socketserver @ https://docs.python.org/2/library/socketserver.html

why size specified 1024 in line self.request.recv(1024) inside handle method. happens if data sent client more 1024 bytes ? better have loop read 1024 bytes until socket empty ? have copied example here :

import socketserver  class mytcphandler(socketserver.baserequesthandler):     """     requesthandler class our server.      instantiated once per connection server, , must     override handle() method implement communication     client.     """      def handle(self):         # self.request tcp socket connected client         self.data = self.request.recv(1024).strip() # why 1024 bytes ?         print "{} wrote:".format(self.client_address[0])         print self.data         # send same data, upper-cased         self.request.sendall(self.data.upper())  if __name__ == "__main__":     host, port = "localhost", 9999      # create server, binding localhost on port 9999     server = socketserver.tcpserver((host, port), mytcphandler)      # activate server; keep running until     # interrupt program ctrl-c     server.serve_forever() 

when reading socket it's required make loop.

the reason if source sent 300 bytes on network it's possible example data arrive receiver 2 separate chunks of 200 bytes , 100 bytes.

for reason when specify buffer size recv maximum amount you're willing process, actual data amount returned may smaller.

there no way implement "read until end of message" @ python level because send/recv functions wrappers of tcp socket interface , stream interface, without message boundaries (so there no way know if "all" data has been received source).

this means in many cases need add own boundaries if need talk using messages (or need use higher-level message-based network transport interface 0mq)

note "blocking mode" - when reading socket - defines behavior when there no data received network layer of operating system: in case, when blocking - program wait chunk of data; if non-blocking instead - return without waiting. if there data received computer, recv call returns if passed buffer size bigger - independently of blocking/non-blocking setting.

blocking mode doesn't mean recv call wait buffer filled.

note: python documentation indeed misleading on behavior of recv , fixed soon.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -