今天在windows10环境下使用socket时,报了TypeError: a bytes-like object is required, not 'str'
错误,查了一下是中文编解码的问题。只需要在发送的字符串加上.encode()
方法和接收的字符串时加上 .decode()
方法即可。
报错:
(base) D:\Project\05 Python\01 Socket>python server.py
连接地址: ('192.168.0.102', 11070)
Traceback (most recent call last):
File "server.py", line 11, in <module>
c.send(send_info)
TypeError: a bytes-like object is required, not 'str'
出错源码
'''
服务端:
'''
send_info = '你好,孙悟空!'
c.send(send_info)
'''
客户端:
'''
print(s.recv(1024))
修改:
'''
服务端:
'''
send_info = '你好,孙悟空!'.encode()
c.send(send_info)
'''
客户端:
'''
print(s.recv(1024).decode())
重新运行成功:
完整代码:
'''
服务端 sever.py
'''
import socket
s = socket.socket() # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345 # 设置端口
s.bind((host, port)) # 绑定端口
s.listen(5) # 等待客户端连接
while True:
c, addr = s.accept() # 建立客户端连接。
print('连接地址:', addr)
send_info = '你好,孙悟空!'.encode()
c.send(send_info)
c.close() # 关闭连接
'''
客户端 client.py
'''
import socket # 导入 socket 模块
s = socket.socket() # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345 # 设置端口号
s.connect((host, port))
print(s.recv(1024).decode())
s.close()
参考:
https://www.fujieace.com/python/str-bytes.html
https://edu.aliyun.com/lesson_505_5752?spm=5176.10731542.0.0.7f7f25aePd0o1g#_5752