Python client server communication
I'm trying to send some data from the server to the client, but the client doesn't get all the data.
Server:
def handle( self ):
#self.request.setblocking( 0 )
i = 10;
while True:
if( self.clientname == 'MasterClient' ):
try:
#ans = self.request.recv( 4096 )
#print( 'after recv' )
""" Sendign data, testing purpose """
while i:
mess = str( i );
postbox['MasterClient'].put( self.creatMessage( 0, 0 , mess ) )
i = i - 1
while( postbox['MasterClient'].empty() != True ):
sendData = postbox['MasterClient'].get_nowait()
a = self.request.send( sendData )
print( a );
#dic = self.getMessage( sendData )
#print 'Sent:%s\n' % str( dic )
except:
mess = str( sys.exc_info()[0] )
postbox['MasterClient'].put( self.creatMessage( 1, 0 , mess ) )
pass
Client:
def run( self ):
sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
addr = ( self.ip, self.port )
#print addr
sock.connect( addr )
#sock.setblocking( 0 )
while True:
try:
ans = sock.recv( 4096 ) 开发者_StackOverflow社区
dic = self.getMessage( ans )
self.recvMessageHandler( dic )
print 'Received:%s\n' % str( dic )
except:
print "Unexpected error:", sys.exc_info()[0]
Where did I make the mistake?
Reads are not symmetrical with writes when using TCP, very often the receiving OS will return much smaller chunks of data than the sending side sends out. A common solution is to prefix each send with a fixed-size integer that contains the length of the next message. The pattern for receiving a complete message then becomes:
bin = sock.recv(4) # for 4-byte integer
mlen = struct.unpack('I', bin)[0]
msg = ''
while len(msg) != mlen:
chunk = sock.recv(4096) # 4096 is an arbitrary buffer size
if not chunk:
raise Exception("Connection lost")
msg += chunk
Make sure you are receiving all data as it's not guaranteed to be sent in a single chunk. For example:
data = ""
while True:
chunk = sock.recv(4096)
if not chunk:
break
data += chunk
精彩评论