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

时间:2021-11-07 15:30:22

错误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()