我正在尝试使用python socket lib进行聊天。当第一个客户端连接到服务器时,它可以正常工作,但是当第二个客户端连接时,第一个客户端将不再向服务器发送消息,但仍会接收客户端2消息。
服务器端代码:
import socket
import threading
class Server:
def __init__(self, port, address):
self.port = port
self.address = address
self.connections = []
self.threads = []
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def handler_connection(self, connection, client_address):
while True:
data = connection.recv(1024)
for connection in self.connections:
connection.send(bytes(data))
if not data:
self.connections.remove(connection)
connection.close()
break
def run(self):
self.sock.bind((self.address, self.port))
self.sock.listen(1)
print('SERVER LISTENING!\naddress: {}\nport {}'.format(self.address, self.port))
def start(self):
while True:
connection, client_address = self.sock.accept()
c_thread = threading.Thread(target=self.handler_connection, args=(connection, client_address))
c_thread.daemon = True
self.threads.append(c_thread)
c_thread.start()
self.connections.append(connection)
print(self.connections)
客户端代码:
import socket
import threading
class Client:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def __init__(self, address):
self.address = address
def receive(self):
while True:
data = self.sock.recv(1024)
if not data:
break
print(data)
def start(self):
self.sock.connect((self.address, 5000))
i_thread = threading.Thread(target=self.receive)
i_thread.daemon = True
i_thread.start()
while True:
self.sock.send(bytes(input('> '), 'utf-8'))