簡體   English   中英

UnicodeDecodeError: 'utf-8' 編解碼器無法解碼位置 3 中的字節 0x95:無效的起始字節 (Python) 套接字編程

[英]UnicodeDecodeError: 'utf-8' codec can't decode byte 0x95 in position 3: invalid start byte (Python) socket programming

我的代碼出現以下錯誤:

 bytes_length = int(len_message.decode())
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x95 in position 3: invalid start byte

客戶端.py

import socket
import threading
import os

def Main():
    host = '127.0.0.1' #IP Address of the system which has the software sending TCP data
    port = 2055 #TCP port number used by the software
    s = socket.socket()
    s.connect((host,port))

    i = 0
    #for i < 2:
    len_message = s.recv(4)
    print(len_message)
    while len_message:
        bytes_length = int(len_message.decode())
        #data_length = (bytes_length + 3)
        print(bytes_length)
        #print(data_length)
        data = s.recv(bytes_length)
        print(data)
        write_file(data)
        len_message = s.recv(4)
    #i+=1
    s.close()

def write_file(data):
        with open("Output.txt", "ab") as text_file:
            text_file.write(data)
            text_file.write('\n'.encode())


if __name__ == '__main__':
    Main()

len_message 是 b'\\x00\\x00\\x06\\x95' 我正在嘗試解碼。 我不明白為什么我會收到這個錯誤。 請幫忙。 提前致謝。

len_message.decode()嘗試將len_message解釋為 unicode 字符串,而從您的上下文來看,這 4 個字節似乎直接是整數表示。

您可以按如下方式獲取字節長度:

bytes_length = int.from_bytes(len_message, 'big') # assuming big-endian bytes order.

對於您顯示的字節, bytes_length將為1685

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM