Tom*_*hal 5 python sockets tcp
我正在构建此套接字应用程序,每次都会收到以下错误:
UnicodeDecodeError: 'utf-8' codec can't Decode byte 0xff inposition 0: invalid start byte
以下是来自服务器的相关行:
filename = client_sock.recv(1024).decode()
filesize = client_sock.recv(1024).decode()
Run Code Online (Sandbox Code Playgroud)
以下是来自客户的相关行:
self.sock.send(file_dir.encode())
self.sock.send(str(filesize).encode())
Run Code Online (Sandbox Code Playgroud)
错误消息出现在服务器的第二行。(filesize =) 以下打印显示客户端将发送到服务器的内容。
print(file_dir) # Output is D:/Statispic2/Photos/photo3.jpg
print(filesize) # Output is 96523
Run Code Online (Sandbox Code Playgroud)
这个错误只是有时发生,这真的很奇怪。我看过其他提出类似问题的问题,但他们的解决方案要么不起作用,要么不相关。
如果您想查看完整代码或有任何其他问题,请告诉我!多谢!
发生错误是因为该字节无法解码为 utf-8,您可以将其作为异常处理,在异常处理中将其解码为“utf-16”:
filename = client_sock.recv(1024)
filesize = client_sock.recv(1024)
try:
decoded_filename = filename.decode()
decoded_filesize = filename.decode()
except UnicodeDecodeError:
decoded_filename = filename.decode('utf-16')
decoded_filesize = filename.decode('utf-16')
Run Code Online (Sandbox Code Playgroud)
或者,您可以在解码过程中忽略异常,但不推荐这样做......
filename = client_sock.recv(1024).decode("utf-8", "ignore")
filesize = client_sock.recv(1024).decode("utf-8", "ignore")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5765 次 |
| 最近记录: |