|
| 1 | +import socket |
| 2 | +import argparse |
| 3 | +import multiprocessing |
| 4 | + |
| 5 | + |
| 6 | +def client(server, port): |
| 7 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 8 | + sock.bind((server, port)) |
| 9 | + sock.listen() |
| 10 | + while True: |
| 11 | + print("Waiting for new connection") |
| 12 | + conn, addr = sock.accept() |
| 13 | + print("Connection from " + str(addr)) |
| 14 | + conn.settimeout(5.0) |
| 15 | + keepGoing = True |
| 16 | + while keepGoing: |
| 17 | + try: |
| 18 | + payload = conn.recv(1024) |
| 19 | + except TimeoutError: |
| 20 | + keepGoing = False |
| 21 | + if len(payload) > 0: |
| 22 | + print(payload.decode(), end='') |
| 23 | + conn.close() |
| 24 | + print() |
| 25 | + |
| 26 | +if __name__ == "__main__": |
| 27 | + |
| 28 | + parser = argparse.ArgumentParser( |
| 29 | + description='TCP Server') |
| 30 | + |
| 31 | + parser.add_argument('-server', type=str, default="", |
| 32 | + help='Host Name or IP Address (e.g. 127.0.0.1 localhost)') |
| 33 | + |
| 34 | + parser.add_argument('-port', type=int, default=2948, |
| 35 | + help='TCP Port Number') |
| 36 | + |
| 37 | + args = parser.parse_args() |
| 38 | + |
| 39 | + if (args.server != ""): |
| 40 | + print("Listening on " + args.server + ":" + str(args.port)) |
| 41 | + else: |
| 42 | + print("Listening on port " + str(args.port)) |
| 43 | + |
| 44 | + proc = multiprocessing.Process(target = client, args = (args.server, args.port)) |
| 45 | + proc.start() |
| 46 | + |
| 47 | + try: |
| 48 | + while True: |
| 49 | + pass |
| 50 | + except KeyboardInterrupt: |
| 51 | + proc.terminate() |
0 commit comments