Python Socket 遇到錯誤: TypeError: a bytes-like object is required, not 'str'


錯誤TypeError: a bytes-like object is required, not 'str'

運行環境:python 3.6.7 + pythoncharm

  錯誤:TypeError: a bytes-like object is required, not 'str'

  錯誤原因:從字面意思已經說明是“需要一個字節類型的數據,而不是一個String類型”,反復找了才發現是我使用send()發送數據時候不能直接填寫字符串,需要轉成字節類型才行。

  格外說下:

      encode()

      decode()兩個方法的使用encode()是可以將String類型的數據轉化成字節類型的。而decode()是將字節型轉化為String類型里面帶參數字符偏碼。

  解決辦法:

  客戶端正確代碼:

# encoding=utf8
from socket import *
from threading import *
from time import *
#方法區域
def receive_msg():
    print('發送消息方法')

def get_host_ip():
    try:
        s = socket(family=AF_INET,type=SOCK_DGRAM)
        s.connect(('8.8.8.8',80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip
#客戶端
def ClientMain():
    host = get_host_ip()
    print(host)
    prot = 8888
    address = (host, prot)
    # 客戶端
    clientSocket = socket(family=AF_INET,type=SOCK_STREAM)
    # 連接到服務器
    clientSocket.connect(address)
    # # 創建線程
    # t = Thread(target=receive_msg, args=('唐烈', clientSocket))
    # # 啟動線程
    # t.start()
    str = "客戶端測試數據"
    # encode()返回是一個bytes類型的數據,發送時候發的是字節流所以不能直接發String  clientSocket.send(str.encode())
    data = clientSocket.recv(1024).decode(encoding='utf-8')

    print('服務端數據:' + str)

if __name__ == '__main__':
    ClientMain()

 

  錯誤代碼:

"D:\softwae install\PythonInsert\python3.6.7\python.exe" "G:/Learning software/Test/Client.py"
Traceback (most recent call last):
  File "G:/Learning software/Test/Client.py", line 39, in <module>
    ClientMain()
  File "G:/Learning software/Test/Client.py", line 33, in ClientMain
    clientSocket.send(str)
TypeError: a bytes-like object is required, not 'str'

 

  相關代碼:

  客戶端錯誤代碼:

# encoding=utf8
from socket import *
from threading import *
from time import *
#方法區域
def receive_msg():
    print('發送消息方法')

def get_host_ip():
    try:
        s = socket(family=AF_INET,type=SOCK_DGRAM)
        s.connect(('8.8.8.8',80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip
#客戶端
def ClientMain():
    host = get_host_ip()
    print(host)
    prot = 8888
    address = (host, prot)
    # 客戶端
    clientSocket = socket(family=AF_INET,type=SOCK_STREAM)
    # 連接到服務器
    clientSocket.connect(address)
    # # 創建線程
    # t = Thread(target=receive_msg, args=('唐烈', clientSocket))
    # # 啟動線程
    # t.start()
    str = "客戶端測試數據"
    # encode()返回是一個bytes類型的數據,發送時候發的是字節流所以不能直接發String
    clientSocket.send(str)
    data = clientSocket.recv(1024).decode(encoding='utf-8')

    print('服務端數據:' + str)

if __name__ == '__main__':
    ClientMain()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM