2016-06-30 10:11:33 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
2022-09-23 00:54:12 +02:00
|
|
|
"""Listener thread creates connection objects for incoming connections"""
|
2016-06-30 10:11:33 +02:00
|
|
|
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):
|
2022-09-23 00:54:12 +02:00
|
|
|
"""The listener thread"""
|
2016-06-30 10:11:33 +02:00
|
|
|
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)
|
2016-08-03 19:01:36 +02:00
|
|
|
|
|
|
|
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()
|
|
|
|
except socket.timeout:
|
2023-09-01 05:03:45 +02:00
|
|
|
continue
|
|
|
|
|
|
|
|
logging.info('Incoming connection from: %s:%i', *addr[:2])
|
|
|
|
with shared.connections_lock:
|
|
|
|
if len(shared.connections) > shared.connection_limit:
|
|
|
|
conn.close()
|
|
|
|
else:
|
|
|
|
c = Connection(*addr[:2], conn, server=True)
|
|
|
|
c.start()
|
|
|
|
shared.connections.add(c)
|
2024-08-25 14:15:14 +02:00
|
|
|
c = None
|