2011-06-16 165 views
1

我試圖從服務器發送一些數據到客戶端,但客戶端並沒有得到所有的數據。Python客戶端服務器通信

服務器:

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] 

哪裏我犯這樣的錯誤?

回答

1

讀取使用TCP時,很多時候比發送側發送出接收OS將返回數據的小得多塊是不對稱的寫入。一個常見的解決方案是使用包含下一條消息長度的固定大小的整數爲每個發送加上前綴。接收完整消息的模式然後變成:

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 
1

確保您收到所有數據,因爲它不能保證以單個塊發送。例如:

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