raceback (most recent call last):
??File "D:\pycharmcode\client.py", line 12, in <module>
????tcp_socket.send(send_data)
TypeError: a bytes-like object is required, not 'str'
使用socket進行ubuntu與windows通信時,發送數據時報了以上錯誤
解決辦法是:
這個錯誤表示在使用 TCP socket 的 send() 方法發送數據時,傳入的參數類型錯誤,需要 bytes-like 對象,而傳入的是 str。在 Python 3 中,socket 模塊的 send() 和 recv() 方法需要傳入和返回 bytes 對象,不能直接處理字符串。解決方法是:1. 使用 str.encode() 方法對字符串進行編碼:
python send_data = "hello server".encode("utf-8") tcp_socket.send(send_data)
2. 直接使用 bytes 字面量:
python send_data = b"hello server" tcp_socket.send(send_data)
3. 如果服務端是 Python 2,可使用 str,添加編碼聲明:
python # -*- coding: utf-8 -*-send_data = "hello server" tcp_socket.send(send_data)
所以正確的做法是調用 encode() 或者直接使用 bytes 對象,將需要發送的數據統一轉換為字節后再發出。同理,在接收數據時需要對 recv() 獲取的字節數據解碼為字符串