summaryrefslogtreecommitdiffstats
path: root/lab_control/test/mock/virtual_tcp_server.py
blob: 07a43455aaa77c88a9df27a0388e4b37598de900 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import socket
import threading
import atexit

IP = "0.0.0.0"
PORT = 5025

# Bind server socket when this module is included
_serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_serverSocket.bind((IP, PORT))
_serverSocket.listen(1)

# Close it when the program exits
def _cleanUp():
    _serverSocket.close()
atexit.register(_cleanUp)

class VirtualTCPServer:
    def __init__(self):
        self._stopFlag = False
        self._clientSocket = None
        self._mainThread = threading.Thread(target=self._mainLoop)
        self._mainThread.start()

    def _mainLoop(self) -> None:
        self._clientSocket, _ = _serverSocket.accept()
        self._clientSocket.settimeout(0.1)

        try:
            while not self._stopFlag:
                try:
                    request = self._clientSocket.recv(4096).decode()
                    response = self._handleRequest(request.strip())
                    if response is not None:
                        self._clientSocket.send(response.encode())
                except TimeoutError as e:
                    pass
        finally:
            self._clientSocket.close()
    
    def stop(self) -> None:
        self._stopFlag = True
        self._mainThread.join()