python socket服务器非阻塞代码示例
时间: 2023-10-07 09:09:24 浏览: 104
使用Python的Twisted框架构建非阻塞下载程序的实例教程
以下是一个 Python Socket 服务器非阻塞代码示例:
```
import socket
import select
# 创建一个非阻塞 Socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setblocking(0)
# 绑定 Socket
server_socket.bind(('localhost', 8888))
# 监听 Socket
server_socket.listen(5)
# 创建一个 Select 对象
select_obj = select.select([server_socket], [], [])
# 开始接收连接
while True:
# 获取已经就绪的 Socket
ready_to_read, _, _ = select_obj.select()
for sock in ready_to_read:
# 如果是 Server Socket 则接受新连接
if sock == server_socket:
client_socket, client_address = server_socket.accept()
print("Got connection from", client_address)
client_socket.setblocking(0)
select_obj.add(client_socket)
else:
# 否则是新数据,读取数据并发送回客户端
data = sock.recv(1024)
if data:
sock.sendall(data)
else:
select_obj.remove(sock)
sock.close()
```
阅读全文