1#! /usr/bin/env python
2
3# Client and server for udp (datagram) echo.
4#
5# Usage: udpecho -s [port]            (to start a server)
6# or:    udpecho -c host [port] <file (client)
7
8import sys
9from socket import *
10
11ECHO_PORT = 50000 + 7
12BUFSIZE = 1024
13
14def main():
15    if len(sys.argv) < 2:
16        usage()
17    if sys.argv[1] == '-s':
18        server()
19    elif sys.argv[1] == '-c':
20        client()
21    else:
22        usage()
23
24def usage():
25    sys.stdout = sys.stderr
26    print 'Usage: udpecho -s [port]            (server)'
27    print 'or:    udpecho -c host [port] <file (client)'
28    sys.exit(2)
29
30def server():
31    if len(sys.argv) > 2:
32        port = eval(sys.argv[2])
33    else:
34        port = ECHO_PORT
35    s = socket(AF_INET, SOCK_DGRAM)
36    s.bind(('', port))
37    print 'udp echo server ready'
38    while 1:
39        data, addr = s.recvfrom(BUFSIZE)
40        print 'server received %r from %r' % (data, addr)
41        s.sendto(data, addr)
42
43def client():
44    if len(sys.argv) < 3:
45        usage()
46    host = sys.argv[2]
47    if len(sys.argv) > 3:
48        port = eval(sys.argv[3])
49    else:
50        port = ECHO_PORT
51    addr = host, port
52    s = socket(AF_INET, SOCK_DGRAM)
53    s.bind(('', 0))
54    print 'udp echo client ready, reading stdin'
55    while 1:
56        line = sys.stdin.readline()
57        if not line:
58            break
59        s.sendto(line, addr)
60        data, fromaddr = s.recvfrom(BUFSIZE)
61        print 'client received %r from %r' % (data, fromaddr)
62
63main()
64