编程使用socket和thread实现多人聊天室(c/s) 要求:界面、接受/发送消息(全双工)
时间: 2024-02-07 17:01:50 浏览: 154
好的,下面是一个基于Python的多人聊天室的代码示例:
服务器端:
```python
import socket
import threading
class Server:
def __init__(self):
self.clients = []
self.host = 'localhost'
self.port = 9999 # 可以修改端口号
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind((self.host, self.port))
self.sock.listen(5)
def broadcast(self, message):
for client in self.clients:
client.send(message.encode())
def handle_client(self, client):
while True:
try:
message = client.recv(1024).decode()
self.broadcast(message)
except:
index = self.clients.index(client)
self.clients.remove(client)
client.close()
self.broadcast(f'Client {index} disconnected')
break
def start(self):
print('Server started')
while True:
client, address = self.sock.accept()
print(f'Connected with {str(address)}')
self.clients.append(client)
thread = threading.Thread(target=self.handle_client, args=(client,))
thread.start()
server = Server()
server.start()
```
客户端:
```python
import socket
import threading
import tkinter as tk
class Client:
def __init__(self):
self.host = 'localhost'
self.port = 9999 # 可以修改端口号
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.host, self.port))
self.gui = tk.Tk()
self.gui.title('Chat Room')
self.chat_history = tk.Text(self.gui)
self.chat_history.pack()
self.message_entry = tk.Entry(self.gui)
self.message_entry.pack()
self.send_button = tk.Button(self.gui, text='Send', command=self.send_message)
self.send_button.pack()
def receive_message(self):
while True:
try:
message = self.sock.recv(1024).decode()
self.chat_history.insert(tk.END, f'{message}\n')
except:
self.sock.close()
break
def send_message(self):
message = self.message_entry.get()
self.message_entry.delete(0, tk.END)
self.sock.send(message.encode())
def start(self):
receive_thread = threading.Thread(target=self.receive_message)
receive_thread.start()
self.gui.mainloop()
client = Client()
client.start()
```
在运行代码之前,需要先安装tkinter库,它是Python的标准GUI库,可以用于创建窗口化的应用程序。
在运行服务器端代码之后,可以启动多个客户端来连接聊天室,每个客户端都可以发送/接收消息,并将它们广播到所有连接到聊天室的客户端。需要注意的是,如果客户端断开连接,则服务器端需要将该客户端从客户端列表中移除,并将一个断开连接的消息广播给所有客户端。
阅读全文