#!/usr/bin/env python3 # coding: utf8 import json import logging import logging.config import os import socket #### logging #### # json decoder for int keys import threading class Decoder(json.JSONDecoder): def decode(self, s, **kwargs): result = super().decode(s) # result = super(Decoder, self).decode(s) for Python 2.x return self._decode(result) def _decode(self, o): if isinstance(o, str): try: return int(o) except ValueError: return o elif isinstance(o, dict): return {k: self._decode(v) for k, v in o.items()} elif isinstance(o, list): return [self._decode(v) for v in o] else: return o def setup_logging(default_path='log_config.json', default_level=logging.INFO, env_key='LOG_CFG'): """Setup logging configuration """ path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: config = json.load(f) logging.config.dictConfig(config) else: logging.basicConfig(level=default_level) setup_logging() log_server = logging.getLogger('server') debug = log_server.debug info = log_server.info warning = log_server.warning error = log_server.error critical = log_server.critical #### Variables #### HOST = '' PORT = 8888 BUFFER_SIZE = 4096 #### Socket #### main_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) main_socket.bind((HOST, PORT)) #### Threads #### class clientThread(threading.Thread): """Main thread, for each client""" def __init__(self, clientsocket, ip, port): """Create clientThread object :param clentsocket: Client's socket :param ip: Client's ip address :param port: Client's connection PORT :type clientsocket: socket.socket :type ip: str :type port: int :return: Nothing :rtype: NoneType""" debug("Creation du thread pour %s" % ip) threading.Thread.__init__(self) # initialisation du thread self.client = clientsocket self.ip = ip self.port = port debug("Creation du thread pour %s reussie" % ip) def run(self): # main de la connection du client """Run thread mainloop :return: Nothing :rtype: NoneType""" ### ICI ON MET LA BOUCLE PRINCIPALE DE CONNECTION self.client.close() if __name__ == "__main__": clients = [] while True: main_socket.listen(1) # ecoutes des connections entrantes clientsocket, (ip, PORT) = main_socket.accept() newClient = clientThread(clientsocket, ip, PORT) newClient.start() clients.append(newClient)