Python客户端与服务器通信

1 投票
2 回答
972 浏览
提问于 2025-04-16 19:41

我正在尝试把一些数据从服务器发送到客户端,但客户端没有收到所有的数据。

服务器代码:

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

客户端代码:

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 )                
                dic = self.getMessage( ans )               
                self.recvMessageHandler( dic )  
                print 'Received:%s\n' % str( dic )       
            except:
               print "Unexpected error:", sys.exc_info()[0]

我哪里出错了?

2 个回答

1

确保你接收到的所有数据都是完整的,因为数据不一定会一次性发送过来。比如说:

data = ""
while True:
    chunk = sock.recv(4096)
    if not chunk:
        break
    data += chunk
1

在使用TCP时,读取数据和写入数据并不是对称的。通常情况下,接收方的操作系统会返回比发送方发送的数据要小得多的数据块。一个常见的解决办法是在每次发送数据前,先发送一个固定大小的整数,这个整数表示接下来要发送的消息的长度。这样,在接收完整消息时的处理方式就变成了:

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

撰写回答