请用python写一个多人聊天室服务器
时间: 2023-01-11 07:55:36 浏览: 161
python实现多人聊天室
好的,这是一个简单的多人聊天室服务器的例子:
```
import threading
import socket
class ChatServer:
def __init__(self, host='127.0.0.1', port=5555):
self.host = host
self.port = port
self.clients = []
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen()
def broadcast(self, message):
for client in self.clients:
client.send(message)
def handle(self, client):
while True:
try:
message = client.recv(1024).decode('utf-8')
if message == '!quit':
client.close()
self.clients.remove(client)
client.join()
break
self.broadcast(message)
except:
client.close()
self.clients.remove(client)
client.join()
break
def receive(self):
while True:
client, address = self.server.accept()
client.send('Welcome to the chat room!'.encode('utf-8'))
self.clients.append(client)
client.start_new_thread(self.handle, (client,))
def start(self):
print('Server listening on {}:{}'.format(self.host, self.port))
self.receive()
if __name__ == '__main__':
ChatServer().start()
```
这是服务器端的代码。客户端可以使用类似的方式连接到服务器并发送和接收消息。
希望这对你有帮助。
阅读全文