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