Python客户端服务器通信

时间:2011-06-16 10:56:16

标签: python client-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

客户端:

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 个答案:

答案 0 :(得分:1)

确保您收到所有数据,因为无法保证在一个块中发送。例如:

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

答案 1 :(得分: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