/ simple_test.py
simple_test.py
1 I'll provide you with a simple example of a Python server using socket programming, which accepts commands from clients, executes them on the server, includes basic error handling, and logs the interactions for debugging purposes. This server uses the `socket` library for communication and `logging` library for logging. 2 3 ```python 4 import sys 5 import socket 6 import logging 7 from threading import Thread 8 9 class Server: 10 def __init__(self, host='127.0.0.1', port=54321): 11 self.host = host 12 self.port = port 13 self.server = None 14 self.clients = {} 15 self.logger = logging.getLogger(__name__) 16 17 def setup_logging(self): 18 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 19 console_handler = logging.StreamHandler() 20 console_handler.setLevel(logging.INFO) 21 console_handler.Formatter = formatter 22 self.logger.handlers = [console_handler] 23 self.logger.setLevel(logging.INFO) 24 25 def start(self): 26 self.setup_logging() 27 self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 28 self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 29 self.server.bind((self.host, self.port)) 30 self.server.listen() 31 32 print("Server started on {}:{}".format(self.host, self.port)) 33 34 while True: 35 connection, address = self.server.accept() 36 client_thread = ClientThread(connection, self.clients) 37 client_thread.start() 38 self.clients[client_thread] = address 39 40 class ClientThread(Thread): 41 def __init__(self, connection, clients): 42 Thread.__init__(self) 43