在Python中学习套接字时,我遇到了一个问题,下面是代码:
server.py
import socket
from threading import Thread
import time
def client_thread(c):
while True:
data = c.recv(1024)
if not data:
break
print('Data received from client: ' + data.decode('utf-8'))
time.sleep(1)
c.send('Thank you!'.encode('utf-8'))
break
c.close()
print('CONNECTION ENDED')
time.sleep(1)
host = socket.gethostname()
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
print('Waiting for connection...')
s.listen(5)
while True:
c, addr = s.accept()
print('Connected to: ' + str(addr))
Thread(target=client_thread, args=(c,)).start()
s.close()
client.py
import socket
import time
host = socket.gethostname()
port = 5000
time.sleep(2)
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect((host, port))
print('Connected!')
time.sleep(1)
msg = input('Send data to server: ')
c.send(msg.encode('utf-8'))
while True:
data = c.recv(1024)
if not data:
break
print('Data received from server: ' + data.decode('utf-8'))
c.close()
我不确定如何一次运行两个客户端,所以我在终端中尝试了此操作(如果操作不正确,请更正):
$ python server.py & python client.py & python client.py
然后我得到了错误:
Waiting for connection...
Connected to: ('127.0.0.1', 43952)
Connected!
Connected to: ('127.0.0.1', 43953)
Connected!
Send data to server: Send data to server: Traceback (most recent call last):
File "client.py", line 16, in <module>
msg = input('Send data to server: ')
EOFError: EOF when reading a line
CONNECTION ENDED
我认为一次运行两个input()有问题
如何在同一设备上一次运行多个客户端?