summaryrefslogtreecommitdiff
path: root/examples/tcp_echo.py
blob: 39db5cca6d7dc4d277c3842da491708da58569a4 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python3
"""TCP echo server example."""
import argparse
import tulip
try:
    import signal
except ImportError:
    signal = None


class EchoServer(tulip.Protocol):

    TIMEOUT = 5.0

    def timeout(self):
        print('connection timeout, closing.')
        self.transport.close()

    def connection_made(self, transport):
        print('connection made')
        self.transport = transport

        # start 5 seconds timeout timer
        self.h_timeout = tulip.get_event_loop().call_later(
            self.TIMEOUT, self.timeout)

    def data_received(self, data):
        print('data received: ', data.decode())
        self.transport.write(b'Re: ' + data)

        # restart timeout timer
        self.h_timeout.cancel()
        self.h_timeout = tulip.get_event_loop().call_later(
            self.TIMEOUT, self.timeout)

    def eof_received(self):
        pass

    def connection_lost(self, exc):
        print('connection lost:', exc)
        self.h_timeout.cancel()


class EchoClient(tulip.Protocol):

    message = 'This is the message. It will be echoed.'

    def connection_made(self, transport):
        self.transport = transport
        self.transport.write(self.message.encode())
        print('data sent:', self.message)

    def data_received(self, data):
        print('data received:', data)

        # disconnect after 10 seconds
        tulip.get_event_loop().call_later(10.0, self.transport.close)

    def eof_received(self):
        pass

    def connection_lost(self, exc):
        print('connection lost:', exc)
        tulip.get_event_loop().stop()


def start_client(loop, host, port):
    t = tulip.Task(loop.create_connection(EchoClient, host, port))
    loop.run_until_complete(t)


def start_server(loop, host, port):
    f = loop.start_serving(EchoServer, host, port)
    x = loop.run_until_complete(f)[0]
    print('serving on', x.getsockname())


ARGS = argparse.ArgumentParser(description="TCP Echo example.")
ARGS.add_argument(
    '--server', action="store_true", dest='server',
    default=False, help='Run tcp server')
ARGS.add_argument(
    '--client', action="store_true", dest='client',
    default=False, help='Run tcp client')
ARGS.add_argument(
    '--host', action="store", dest='host',
    default='127.0.0.1', help='Host name')
ARGS.add_argument(
    '--port', action="store", dest='port',
    default=9999, type=int, help='Port number')


if __name__ == '__main__':
    args = ARGS.parse_args()

    if ':' in args.host:
        args.host, port = args.host.split(':', 1)
        args.port = int(port)

    if (not (args.server or args.client)) or (args.server and args.client):
        print('Please specify --server or --client\n')
        ARGS.print_help()
    else:
        loop = tulip.get_event_loop()
        if signal is not None:
            loop.add_signal_handler(signal.SIGINT, loop.stop)

        if args.server:
            start_server(loop, args.host, args.port)
        else:
            start_client(loop, args.host, args.port)

        loop.run_forever()