提问人:KittenDEV 提问时间:2/8/2023 更新时间:2/8/2023 访问量:61
为什么异步套接字在 python3 上不能再接受 1 个客户端?
Why does async socket cannot accept 1 more clients on python3?
问:
我试图为我的私人服务器制作异步套接字核心。这可行,但不要接受超过 1 个客户端。2 个客户端尝试连接,但第二个客户端无法执行此操作,只有当第一个客户端断开连接时才会这样做。
import asyncio, socket, time
class Server:
def __init__(self, port: int):
self.server = socket.socket()
self.port = port
async def start(self):
self.server.bind(("0.0.0.0", self.port))
self.server.listen()
print(f"Server started on {self.port}!")
while True:
session, ip = self.server.accept()
print(f"{ip[0]} connected!")
await Connection(session, ip[0]).messaging()
class Connection:
def __init__(self, session, ip):
self.session = session
self.ip = ip
def receive(self, session, lens):
data = b""
while len(data) < lens:
s = session.recv(lens)
if not s:
s += 0
break
data += s
return data
async def messaging(self):
last = int(time.time())
while True:
try:
header = self.session.recv(7)
if len(header) > 0:
last = int(time.time())
mtype = int.from_bytes(header[:2], "big")
mlen = int.from_bytes(header[2:5], "big")
mdata = self.receive(self.session, mlen)
print(f"[C] {mtype} from {self.ip}")
if int(time.time()) - last > 7:
break
except(ConnectionAbortedError, ConnectionResetError, ConnectionRefusedError, TimeoutError, OSError):
break
self.session.close()
print(f"{self.ip} disconnected!")
asyncio.run(Server(9339).start())
我尝试使用模块选择,但这有滞后的断开连接。
答: 暂无答案
评论
messaging.
messaging
await
messaging