2021-07-13

Python 3.5 Socket TypeError: a bytes-like object is required, not 'str' 错误提示
先介绍一下 python bytes和str两种类型转换的函数encode(),decode()

str通过encode()方法可以编码为指定的bytes
反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法:
服务端代码:
  #!/usr/bin/python
  # -*- coding: UTF-8 -*-
  # 文件名:server.py
 import socket               # 导入 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)
  c.send(('迎访问菜鸟教程!').encode())
  c.close()                # 关闭连接

客户端代码:

 #!/usr/bin/python
# -*- coding: UTF-8 -*-
 # 文件名: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()

猜你喜欢

转载自blog.csdn.net/abc1231987/article/details/118691841