python socket的send不能发送字符串解决办法
sever.py
import socket s = socket.socket() host = socket.gethostname() port = 13323 s.bind((host,port)) s.listen(5) while True: c,addr = s.accept() print('连接地址:',addr) str1 = '欢迎' c.send(str1) c.close()
client.py
import socket s = socket.socket() host = socket.gethostname() port = 13323 s.connect((host,port)) print(s.recv(1024)) s.close()
分别运行之后sever.py报错
Traceback (most recent call last): File ".\server.py", line 11, in <module> c.send(str1) TypeError: a bytes-like object is required, not 'str'
解决办法:
sever.py改为
import socket s = socket.socket() host = socket.gethostname() port = 13323 s.bind((host,port)) s.listen(5) while True: c,addr = s.accept() print('连接地址:',addr) str1 = '欢迎' c.send(str1.encode("utf8")) c.close()
client.py改为
import socket s = socket.socket() host = socket.gethostname() port = 13323 s.connect((host,port)) print(s.recv(1024).decode()) s.close()
分别运行后:
client.py输出
欢迎