2016-04-20 19 views
0

Ich brauche 16-Bit-Ganzzahlen aus einem TCP-Paket. Wie bekomme ich es zur Arbeit? Ich habe Schwierigkeiten, meinen Datentyp richtig zu bekommen.Neu in Python Bytes in Python 2.4.3

HOST = 'localhost' 
PORT = 502 
#s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
s.bind((HOST,PORT)) 
s.listen(1) 
conn, addr = s.accept() 
data = [] 
data = conn.recv(1024) 
print 'Connect by', addr 
while (data): 
    sys.stdout.write(hexdump(data)) 
    sys.stdout.write(struct.unpack("h", data[2:4])) # here is error!!!! 
    data = conn.recv(1024) 

I get this error when running: 
Connect by ('127.0.0.1', 52741) 
0000 00 27 00 00 00 06 01 03 00 00 00 0a    .'.......... 
KeyError: 4784 
Press any key to continue . . . 

Wie kann ich meine Variablenarten verbessern, so kann ich Ganzzahlen 16 und 32 Bit aus TCP-Paket ziehen

+0

folgt Wie funktioniert es nicht? Bitte zeigen Sie den gesamten Traceback an. Es gibt nichts Offensichtliches in dem gezeigten Code, der 'KeyError: 4784' erzeugen würde. – martineau

Antwort

0
data[2:2] # this is your issue (it is an empty string always) ... not sure what you want here 
print repr("Hello"[2:2]) # this is no bytes of string 
print repr("hello"[2:4]) # this is 2 bytes of string 

# you need 2 bytes to unpack a short 
print struct.unpack("h","") # error!! 
print struct.unpack("h","b") # error!! 
print struct.unpack("h","bq") # ok awesome! 

# you also cannot have too many bytes 
print struct.unpack("h","bbq") # error!!!!!!! 

#but you can use unpack_from to just take the bytes you define 
print struct.unpack_from("h","bbq") # ok awesome again! 

Sie können den kurzen Wert aller Ihrer Bytes auszudrucken als

while data: 
    sys.stdout.write(struct.unpack_from("h", data)) # print this short 
    data = data[2:] # advance the buffer to the next short 
+0

Ja, ich habe es funktioniert. Ich verwende ein älteres Python in einem eingebetteten System. Die Struktur funktioniert. Vielen Dank!!!! –