summaryrefslogtreecommitdiff
path: root/examples/udp_echo.py
blob: 5d1e02ecc004dc71d4d775f07691f7c01a01e4ee (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
"""UDP echo example.

Start server:

  >> python ./udp_echo.py --server

"""

import sys
import tulip

ADDRESS = ('127.0.0.1', 10000)


class MyServerUdpEchoProtocol:

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

    def datagram_received(self, data, addr):
        print('Data received:', data, addr)
        self.transport.sendto(data, addr)

    def connection_refused(self, exc):
        print('Connection refused:', exc)

    def connection_lost(self, exc):
        print('stop', exc)


class MyClientUdpEchoProtocol:

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

    def connection_made(self, transport):
        self.transport = transport
        print('sending "{}"'.format(self.message))
        self.transport.sendto(self.message.encode())
        print('waiting to receive')

    def datagram_received(self, data, addr):
        print('received "{}"'.format(data.decode()))
        self.transport.close()

    def connection_refused(self, exc):
        print('Connection refused:', exc)

    def connection_lost(self, exc):
        print('closing transport', exc)
        loop = tulip.get_event_loop()
        loop.stop()


def start_server():
    loop = tulip.get_event_loop()
    tulip.Task(loop.create_datagram_endpoint(
        MyServerUdpEchoProtocol, local_addr=ADDRESS))
    loop.run_forever()


def start_client():
    loop = tulip.get_event_loop()
    tulip.Task(loop.create_datagram_endpoint(
        MyClientUdpEchoProtocol, remote_addr=ADDRESS))
    loop.run_forever()


if __name__ == '__main__':
    if '--server' in sys.argv:
        start_server()
    else:
        start_client()