python socket 网络聊天室 生成代码
时间: 2023-07-25 11:36:16 浏览: 98
以下是一个简单的 Python 网络聊天室的代码示例:
服务端代码:
```python
import socket
import threading
HOST = '127.0.0.1'
PORT = 65432
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen()
clients = []
def broadcast(message):
for client in clients:
client.sendall(message.encode())
def handle_client(client_socket, client_addr):
clients.append(client_socket)
print(f'Connected by {client_addr}')
while True:
message = client_socket.recv(1024).decode()
if not message:
break
print(f'Received from {client_addr}: {message}')
broadcast(f'{client_addr}: {message}')
clients.remove(client_socket)
client_socket.close()
print(f'Connection closed by {client_addr}')
while True:
client_socket, client_addr = server_socket.accept()
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_addr))
client_thread.start()
```
客户端代码:
```python
import socket
import threading
HOST = '127.0.0.1'
PORT = 65432
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
def receive():
while True:
message = client_socket.recv(1024).decode()
print(message)
receive_thread = threading.Thread(target=receive)
receive_thread.start()
while True:
message = input()
client_socket.sendall(message.encode())
```
这个聊天室采用了基于TCP协议的socket通信,它允许多个客户端连接到服务器并相互通信。服务端在客户端连接时将客户端socket对象添加到一个客户端列表中,然后在收到消息时广播给所有连接的客户端。客户端连接到服务器后,将启动一个接收线程来监听服务器的消息,同时等待用户输入并将消息发送给服务器。
阅读全文