服务器:
import socket
import threading
import sys
sock = socket.socket()
sock.bind(('192.168.0.100', 1080))
sock.listen(3)
conn = []
def Reciver():
while 1:
for i in range(len(conn)):
try:
data = conn[i].recv(1024)
if data:
print(data.decode())
except socket.error as e:
if e.errno == 10053:
conn.pop(i)
print("Подключено пользователй:", len(conn))
else:
raise
def Sender():
while 1:
global conn
message = input()
if message:
for i in range(len(conn)):
conn[i].send(message.encode())
def Accepter():
while 1:
global conn
conn.append(sock.accept()[0])
print("Подключено пользователй:", len(conn))
# init threads
t1 = threading.Thread(target=Reciver)
t2 = threading.Thread(target=Sender)
t3 = threading.Thread(target=Accepter)
# start threads
t1.start()
t2.start()
t3.start()
客户端代码:
import socket
import threading
import sys
host = "192.168.0.100"
port = 1080
sock = socket.socket()
sock.connect((host, port))
def Reciver():
while 1:
data = sock.recv(1024)
if data:
print(data.decode())
def Sender():
while 1:
message = input()
if message == "exit":
sock.close()
sys.exit()
else:
sock.send(message.encode())
# init threads
t1 = threading.Thread(target=Reciver)
t2 = threading.Thread(target=Sender)
# start threads
t1.start()
t2.start()
问题:当连接2个客户端时,发现只有服务端能正常写入,客户端传来bug消息。而当client断开的时候,服务端理解了很久,这就是为什么在断开2的时候,立马出现bug,只断开1,就产生了错误,之后发送消息无论是在服务端还是在服务端都不起作用在客户端..
socket.accept()返回套接字和地址的元组。因此,您需要
conn.append(sock.accept())
将代码更改为conn.append(sock.accept()[0])
,或将代码更改conn[i].send(message.encode())
为conn[i][0].send(message.encode())
。您的代码中还有很多地方应该更改,但它们与此错误没有具体关系。
更新: