nis*_*ist 1 python sockets encoding
我想在python中设置一个小聊天程序.一切都工作正常,直到我发送一个包含非ascii字符的字符串,导致程序崩溃.该字符串是从wx.TestCtrl中读取的
如何通过套接字发送UTF-8编码的字符串?
为什么程序一开始没有问题?我已将编码设置为UTF-8,所以不是所有字符都会导致程序崩溃?
这是错误:
Traceback (most recent call last):
File "./client.py", line 180, in sendMess
outSock.sendto(s,self.serveraddr)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 26:
ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
这是我如何创建套接字并尝试发送消息:
outSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
....
outSock.sendto(s,self.serveraddr)
Run Code Online (Sandbox Code Playgroud)
在Python 2中,socket.sendto
套接字采用"普通"字符串,而不是unicode
对象.因此,您必须对其进行编码,例如使用UTF-8:
outSock.sendto(s.encode('utf-8'), self.serveraddr)
Run Code Online (Sandbox Code Playgroud)
类似地,当您recvfrom
(或类似)在另一端时,您将需要转换回Unicode对象:
unicode_string = s.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)
(在Python 3中,您将使用它bytes
,这需要在它之间进行转换和unicode
更明确.)