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输出

欢迎

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-03-07
  • 2021-06-11
  • 2021-11-20
  • 2022-12-23
  • 2022-12-23
  • 2021-12-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-17
  • 2021-05-18
  • 2021-11-28
相关资源
相似解决方案