diff options
author | Guido van Rossum <guido@python.org> | 1991-07-01 18:32:32 (GMT) |
---|---|---|
committer | Guido van Rossum <guido@python.org> | 1991-07-01 18:32:32 (GMT) |
commit | 22825e86f6e13a4d84822ae9ee7c8a807259f37d (patch) | |
tree | a773c67d671fc73801ebc372e0cf6451192aacb5 /Demo/sockets/udpecho.py | |
parent | 2fa5a7fc00a726c119f7626c702ffb7fa464b25b (diff) | |
download | cpython-22825e86f6e13a4d84822ae9ee7c8a807259f37d.zip cpython-22825e86f6e13a4d84822ae9ee7c8a807259f37d.tar.gz cpython-22825e86f6e13a4d84822ae9ee7c8a807259f37d.tar.bz2 |
Initial revision
Diffstat (limited to 'Demo/sockets/udpecho.py')
-rwxr-xr-x | Demo/sockets/udpecho.py | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/Demo/sockets/udpecho.py b/Demo/sockets/udpecho.py new file mode 100755 index 0000000..53dff64 --- /dev/null +++ b/Demo/sockets/udpecho.py @@ -0,0 +1,63 @@ +#! /usr/local/python + +# Client and server for udp (datagram) echo. +# +# Usage: udpecho -s [port] (to start a server) +# or: udpecho -c host [port] <file (client) + +import sys +from socket import * + +ECHO_PORT = 50000 + 7 +BUFSIZE = 1024 + +def main(): + if len(sys.argv) < 2: + usage() + if sys.argv[1] = '-s': + server() + elif sys.argv[1] = '-c': + client() + else: + usage() + +def usage(): + sys.stdout = sys.stderr + print 'Usage: udpecho -s [port] (server)' + print 'or: udpecho -c host [port] <file (client)' + sys.exit(2) + +def server(): + if len(sys.argv) > 2: + port = eval(sys.argv[2]) + else: + port = ECHO_PORT + s = socket(AF_INET, SOCK_DGRAM) + s.bind('', port) + print 'udp echo server ready' + while 1: + data, addr = s.recvfrom(BUFSIZE) + print 'server received', `data`, 'from', `addr` + s.sendto(data, addr) + +def client(): + if len(sys.argv) < 3: + usage() + host = sys.argv[2] + if len(sys.argv) > 3: + port = eval(sys.argv[3]) + else: + port = ECHO_PORT + addr = host, port + s = socket(AF_INET, SOCK_DGRAM) + s.bind('', 0) + print 'udp echo client ready, reading stdin' + while 1: + line = sys.stdin.readline() + if not line: + break + s.sendto(line, addr) + data, fromaddr = s.recvfrom(BUFSIZE) + print 'client received', `data`, 'from', `fromaddr` + +main() |