MiNode/minode/listener.py

39 lines
1.2 KiB
Python
Raw Normal View History

2016-06-30 10:11:33 +02:00
# -*- coding: utf-8 -*-
import logging
import socket
import threading
2021-03-09 15:40:59 +01:00
from . import shared
from .connection import Connection
2016-06-30 10:11:33 +02:00
class Listener(threading.Thread):
def __init__(self, host, port, family=socket.AF_INET):
super().__init__(name='Listener')
self.host = host
self.port = port
self.family = family
self.s = socket.socket(self.family, socket.SOCK_STREAM)
2016-08-03 13:06:09 +02:00
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2016-06-30 10:11:33 +02:00
self.s.bind((self.host, self.port))
self.s.listen(1)
self.s.settimeout(1)
def run(self):
2016-06-30 10:11:33 +02:00
while True:
2016-10-15 16:12:09 +02:00
if shared.shutting_down:
logging.debug('Shutting down Listener')
break
2016-06-30 10:11:33 +02:00
try:
conn, addr = self.s.accept()
2022-09-23 07:44:55 +02:00
logging.info('Incoming connection from: %s:%i', *addr[:2])
2016-06-30 10:11:33 +02:00
with shared.connections_lock:
2017-01-21 14:05:13 +01:00
if len(shared.connections) > shared.connection_limit:
conn.close()
else:
2022-09-23 07:44:55 +02:00
c = Connection(*addr[:2], conn, server=True)
2017-01-21 14:05:13 +01:00
c.start()
shared.connections.add(c)
2016-06-30 10:11:33 +02:00
except socket.timeout:
pass