socket.io的 Python客户端中文encode问题
socketIO-client是python实现的SocketIO客户端。
问题
当接收到中文消息时出现下方错误,简单说就是编码问题。
Traceback (most recent call last): File "sub.py", line 24, in <module> socketIO.wait() File "/usr/local/lib/python3.5/site-packages/socketIO_client/__init__.py", line 232, in wait self._process_packets() File "/usr/local/lib/python3.5/site-packages/socketIO_client/__init__.py", line 254, in _process_packets for engineIO_packet in self._transport.recv_packet(): File "/usr/local/lib/python3.5/site-packages/socketIO_client/transports.py", line 155, in recv_packet six.b(packet_text)) File "/usr/local/lib/python3.5/site-packages/six.py", line 620, in b return s.encode("latin-1") UnicodeEncodeError: 'latin-1' codec can't encode characters in position 21-27: ordinal not in range(256)
解决方法
找到
socketIO_client
的安装路径,例中跟six.py
在同一目录下,路径是/usr/local/lib/python3.5/site-packages/socketIO_client/
.找到
socketIO_client
文件夹下的transports.py
文件用编辑器打开
transports.py
,在144行左右的位置找到recv_packet
函数def recv_packet(self): try: packet_text = self._connection.recv() except websocket.WebSocketTimeoutException as e: raise TimeoutError('recv timed out (%s)' % e) except websocket.SSLError as e: raise ConnectionError('recv disconnected by SSL (%s)' % e) except websocket.WebSocketConnectionClosedException as e: raise ConnectionError('recv disconnected (%s)' % e) except socket.error as e: raise ConnectionError('recv disconnected (%s)' % e) engineIO_packet_type, engineIO_packet_data = parse_packet_text( six.b(packet_text)) yield engineIO_packet_type, engineIO_packet_data
修改倒数第二行
six.b(packet_text))
为six.u(packet_text))
,修改后保存.再次运行代码接收中文消息,代码正常运行.
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16