#!/usr/bin/env python
# coding: utf-8

import errno, os, socket, sys, time

def server(port, reuseport=True):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if reuseport:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    s.bind(('127.0.0.1', port))
    s.listen(1)
    return s

def connect(port, blocking=True):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setblocking(blocking)
    try:
        s.connect(('127.0.0.1', port))
    except socket.error as e:
        # For non-blocking sockets, EINPROGRESS is expected.
        if not blocking and e.errno == errno.EINPROGRESS:
            pass
        else:
            raise
    return s

def main():
    p = 12346
    i = 0

    if os.fork():
        while True:
            srv = server(p, True)
            c, _ = srv.accept()

            c.close()
            srv.close()

            i += 1
            if i % 10 == 0:
                sys.stderr.write("\r\033[K%d" % i)
    else:
        while True:
            cli = connect(p, False)
            cli.close()

if __name__ == '__main__':
    main()
