2013-07-06 137 views
0

我想通过套接字写一个字节(0-255),但我无法弄清楚如何。Python通过套接字写字节

socket.send(str(unichr(byte)))适用于0-128,然后给出UnicodeEncodeError

无论如何要写一个字节在套接字上吗?提前致谢。

+1

难道你不能只写入字节的套接字,并将其编码字符串在接收端? – Nadh

回答

1

使用正常的字节串。

socket.send('\xa5') 
socket.send('Hello, world!') 

chr()

socket.send(chr(0xa5)) 
0

它实际上不是被赋予错误这是STR功能的插座:

>>> str(unichr(200)) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xc8' in position 0: ordinal not in range(128) 
>>> unicode(unichr(200)) 
u'\xc8' 

尝试发送该网址。

+0

字节应通过套接字发送,而不是文本。 –