Python写一个socket多线程服务器
时间: 2024-03-30 08:15:53 浏览: 174
socket多线程服务器
4星 · 用户满意度95%
好的,以下是一个Python写的多线程服务器的代码示例:
```
import socket
import threading
# 定义一个函数用来处理客户端请求
def handle_client(client_socket, client_address):
print("New connection:", client_address)
while True:
# 接收客户端发来的数据
data = client_socket.recv(1024)
if not data:
break
# 处理数据并回写给客户端
response = data.upper()
client_socket.send(response)
# 关闭客户端连接
print("Connection closed:", client_address)
client_socket.close()
# 定义一个函数用来启动服务器
def run_server():
# 创建一个TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定到指定端口
server_socket.bind(('localhost', 8888))
# 监听客户端连接
server_socket.listen(5)
print('Server started, waiting for client connections...')
while True:
# 等待客户端连接,并创建一个新的线程来处理该连接
client_socket, client_address = server_socket.accept()
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_thread.start()
if __name__ == '__main__':
run_server()
```
阅读全文