2012-05-08 61 views
1

我需要一個python程序來使用TCP連接(到另一個程序)來檢索9個字節的集合。Python套接字接收雙倍

九個字節中的第一個表示一個字符,其餘表示一個字符。

如何從python套接字中提取此信息?我需要手動執行數學轉換流數據還是有更好的方法?

+0

由位你的意思是字節吧? – lukecampbell

回答

0

如果客戶端和服務器都用Python編寫的,我建議你用鹹菜。它可以讓你將python變量轉換爲字節,然後將它們轉換爲原始類型的python變量。

#SENDER 
 
import pickle, struct 
 

 
#convert the variable to bytes with pickle 
 
bytes = pickle.dumps(original_variable) 
 
#convert its size to a 4 bytes int (in bytes) 
 
#I: 4 bytes unsigned int 
 
#!: network (= big-endian) 
 
length = struct.pack("!I", len(bytes)) 
 
a_socket.sendall(length) 
 
a_socket.sendall(bytes)

#RECEIVER 
 
import pickle, struct 
 

 
#This function lets you receive a given number of bytes and regroup them 
 
def recvall(socket, count): 
 
    buf = b"" 
 
    while count > 0: 
 
     newbuf = socket.recv(count) 
 
     if not newbuf: return None 
 
     buf += newbuf 
 
     count -= len(newbuf) 
 
    return buf 
 

 

 
length, = struct.unpack("!I", recvall(socket, 4)) #we know the first reception is 4 bytes 
 
original_variable = pickle.loads(recval(socket, length))