-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent.py
66 lines (58 loc) · 1.47 KB
/
agent.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import argparse
import socket
import threading
# Arguments
parser = argparse.ArgumentParser()
parser.add_argument('--bind-address', type=str, default="0.0.0.0")
parser.add_argument('--bind-port', type=int, default=10914)
NUM_WORKERS = 10
"""
Thread
"""
class ClientThread(threading.Thread):
"""
Constructor
"""
def __init__(self, csock):
threading.Thread.__init__(self)
self.csock = csock
self.running = True
"""
Run this thread
"""
def run(self):
while self.running:
data = self.csock.recv(4096)
self.csock.send(data)
if len(data) == 0:
self.running = False
"""
Main routine
"""
def main(args):
# Open a socket and listen connections on it
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((args.bind_address, args.bind_port))
sock.listen(NUM_WORKERS)
while True:
# Accept a client and start a thread
csock, caddr = sock.accept()
th = ClientThread(csock)
th.start()
# Join dead threads
for th in threading.enumerate():
if th == threading.main_thread():
continue
if not th.is_alive():
th.join()
# Close the socket
sock.close()
return True
"""
Call the main routine
"""
if __name__ == "__main__":
# Parse the arguments
args = parser.parse_args()
main(args)