File: dumb_tcp_server.py

package info (click to toggle)
vim-ale 4.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,764 kB
  • sloc: sh: 499; python: 311; perl: 31; makefile: 4; xml: 4; javascript: 1
file content (40 lines) | stat: -rw-r--r-- 901 bytes parent folder | download | duplicates (3)
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
"""
This Python script creates a TCP server that does nothing but send its input
back to the client that connects to it. Only one argument must be given, a port
to bind to.
"""
import os
import socket
import sys


def main():
    if len(sys.argv) < 2 or not sys.argv[1].isdigit():
        sys.exit('You must specify a port number')

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('127.0.0.1', int(sys.argv[1])))
    sock.listen(0)

    pid = os.fork()

    if pid:
        print(pid)
        sys.exit()

    while True:
        connection = sock.accept()[0]
        connection.settimeout(5)

        while True:
            try:
                connection.send(connection.recv(1024))
            except socket.timeout:
                break

        connection.close()


if __name__ == "__main__":
    main()