MiNode/src/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
from connection import Connection
import shared
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()
logging.info('Incoming connection from: {}:{}'.format(addr[0], addr[1]))
with shared.connections_lock:
2017-01-21 14:05:13 +01:00
if len(shared.connections) > shared.connection_limit:
conn.close()
else:
c = Connection(addr[0], addr[1], conn)
c.start()
shared.connections.add(c)
2016-06-30 10:11:33 +02:00
except socket.timeout:
pass