def run_frontend(self, tcp_address, backlog=10, timeout=0.1):
log.info('Running frontend loop')
address, port = tcp_address.split(':')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.bind((address, int(port)))
sock.listen(backlog)
sock.settimeout(timeout)
while not self.stop_event.is_set():
try:
conn, address = await self.loop.sock_accept(sock)
except socket.timeout:
await asyncio.sleep(timeout)
continue
service = await self.loop.sock_recv(conn, BUFFER_SIZE)
if not service:
break
if service not in self.services:
self.loop.sock_sendall(conn, b'-Service not found\r\n')
continue
# detach and pack FD into a array
fd = conn.detach()
fds = array.array("I", [fd])
try:
# Send FD to server connection
server_conn = self.services[service]
server_conn.sendmsg([b'1'], [(socket.SOL_SOCKET,
socket.SCM_RIGHTS, fds)])
except BrokenPipeError: # NOQA
# If connections is broken, the server is gone
# so we need to remove it from services
del self.services[service]
conn = socket.fromfd(fd, socket.AF_INET,
socket.SOCK_STREAM)
conn.sendall(b'-Service not found\r\n')
conn.close()
评论列表
文章目录