Python UnicodeDecodeError:“ ascii”编解码器无法解码位置的字节0xfc

时间:2019-11-25 18:02:37

标签: python

def handle_client(self, client_socket, address):
    size = 1024
    while True:
        try:
            data = client_socket.recv(size)
            if 'q^' in data.decode():    
                print('Received request for exit from: ' + str(address[0]) + ':' + str(address[1]))
                break

            else: 
                body = data.decode()

        except socket.error:
            client_socket.close()
            return False

    client_socket.sendall('Received request for exit. Deleted from server threads'.encode())
    client_socket.sendall('q^'.encode())
    client_socket.close()

错误发生在if 'q^' in data.decode():

数据来自iOS客户端

connection.send(content: "SOME_STRING".data(using: .utf8)!, completion: NWConnection.SendCompletion.contentProcessed({ error in
                print(error)
            }))

关于SO的问题类似,但没有一种解决方案可以解决问题

1 个答案:

答案 0 :(得分:1)

在客户端,您使用utf-8将字符编码为字节。

在服务器端,您无需指定编码即可将字节解码为字符。根据问题标题中的异常消息,您的环境尝试使用ascii来解码字节。但是,字节对于ASCII无效。您要明确指定编码:

data.decode("utf-8")

在对从python服务器发送的消息进行编码时,还应该指定编码。

我还建议您对收到的每个块仅执行一次decode(),而不要执行两次。

def handle_client(self, client_socket, address):
    size = 1024
    while True:
        try:
            raw_data = client_socket.recv(size)
            data = raw_data.decode('utf-8')
            if 'q^' in data:    
                print('Received request for exit from: ' + str(address[0]) + ':' + str(address[1]))
                break

            else: 
                body = data

        except socket.error:
            client_socket.close()
            return False

    client_socket.sendall('Received request for exit. Deleted from server threads'.encode('utf-8'))
    client_socket.sendall('q^'.encode('utf-8'))
    client_socket.close()