"""
Micropython 没有 queue 请用 deque
from collections import deque
"""
import select, socket, sys, network
from collections import deque
station = network.WLAN(network.STA_IF)
local_ip = station.ifconfig()[0] # IP地址st
tcp_port = 5020 # port to listen for requests/providing data
# Create a TCP/IP socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(socket.AF_INET, socket.SOCK_STREAM) # 2 1
server.setblocking(False)
# Bind the socket to the port
server_address = (local_ip, tcp_port) # localhost = 127.0.0.1/192.168.1.108/
print(sys.stderr, "starting up on %s port %s" % server_address)
server.bind(server_address) # OSError: [Errno 112] EADDRINUSE 稍等退出port重试即可
# Listen for incoming connections
server.listen(5)
# Sockets from which we expect to read
# 开始只有服务端,后面进来新连接再放入监控列表inputs,此列表里面是空就会报错:监控什么?
inputs = [server]
print("初始监控列表里面只有1个服务端 =", inputs)
# Sockets to which we expect to write
outputs = []
message_queues = {}
while inputs:
# Wait for at least one of the sockets to be ready for processing
print("\nwaiting for the next event")
# select接收任务和返回结果依据这3个列表
readable, writable, exceptional = select.select(inputs, outputs, inputs)
# Handle inputs
for s in readable:
# s是服务端,只负责接收新连接,接收数据是connection socket对象的事情
if s is server:
# A "readable" server socket is ready to accept a connection
connection, client_address = s.accept() # 有新连接请求
print("new connection from", client_address)
connection.setblocking(False) # 必须是非阻塞的才能并发
inputs.append(connection) # 新连接交给select监控
# Give the connection a queue for data we want to send
# message_queues字典的Key=connection,Value=专用队列
message_queues[connection] = deque([],10)
else:
data = s.recv(512)
if data:
# A readable client socket has data
# s.getpeername() => AttributeError: 'socket' object has no attribute 'getpeername'
print(sys.stderr, 'received "%s" from %s' % (data, s))
MicroPython单线程多路IO复用select.poll TCPserver透传
于 2025-02-08 15:24:37 首次发布

最低0.47元/天 解锁文章
600

被折叠的 条评论
为什么被折叠?



