python 建立客户端和服务器多线程
时间: 2024-10-12 07:17:13 浏览: 26
在Python中,建立客户端和服务器的多线程通信通常涉及使用`socket`库和`threading`模块。下面是一个简单的例子,展示了如何创建一个基础的TCP服务器和客户端,它们都包含多线程处理连接:
**服务器端(server.py)**:
```python
import socket
import threading
def handle_client(client_socket):
request = client_socket.recv(1024)
print(f"Received: {request.decode('utf-8')}")
client_socket.sendall("Server received".encode('utf-8'))
client_socket.close()
def start_server():
host = 'localhost'
port = 12345
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
print(f"Server is running on {host}:{port}")
while True:
client, addr = server_socket.accept()
print(f"Accepted connection from {addr[0]}:{addr[1]}")
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
start_server()
```
**客户端(client.py)**:
```python
import socket
import threading
def connect_to_server(server_host, server_port):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_host, server_port))
def send_message(message):
client_socket.sendall(message.encode('utf-8'))
response = client_socket.recv(1024).decode('utf-8')
print(f"Response from server: {response}")
message = input("Enter a message to send: ")
sending_thread = threading.Thread(target=send_message, args=(message,))
sending_thread.start()
connect_to_server('localhost', 12345)
```
在这个例子中,服务器启动一个监听套接字,并在一个新线程中处理每个新连接的客户端请求。客户端也创建一个单独的线程来发送消息。
阅读全文