用python搭建一个聊天室
时间: 2024-10-02 08:02:19 浏览: 43
用Python搭建一个简单的聊天室可以借助`socket`库,因为socket提供了一种在本地计算机之间建立通信的方式。下面是一个基本的客户端服务器模型的示例:
**服务器端(server.py):**
```python
import socket
def start_server():
host = 'localhost'
port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(5) # 监听连接,最大5个连接
print(f'Server is running on {host}:{port}')
while True:
client, addr = server.accept() # 接受新连接
print(f'Accepted connection from {addr[0]}:{addr[1]}')
request = client.recv(1024).decode('utf-8') # 接收消息
print(f'Received message: {request}')
response = 'You said: {}'.format(request) # 回复消息
client.sendall(response.encode('utf-8')) # 发送回复
if __name__ == "__main__":
start_server()
```
**客户端(client.py):**
```python
import socket
def start_client(host, port):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
client.send('Hello, Server!'.encode('utf-8'))
received_msg = client.recv(1024).decode('utf-8')
print(f'Received: {received_msg}')
client.close()
if __name__ == "__main__":
host = input('Enter the server address (localhost): ')
port = int(input('Enter the server port (default 9999): ') or 9999)
start_client(host, port)
```
运行服务器端程序,然后启动几个客户端连接到该服务器。每个客户端都能发送和接收消息。
阅读全文