1996-11-27 15:52:01 -04:00
|
|
|
#! /usr/bin/env python
|
1991-07-01 15:32:32 -03:00
|
|
|
|
|
|
|
# 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():
|
2004-07-18 02:56:09 -03:00
|
|
|
if len(sys.argv) < 2:
|
|
|
|
usage()
|
|
|
|
if sys.argv[1] == '-s':
|
|
|
|
server()
|
|
|
|
elif sys.argv[1] == '-c':
|
|
|
|
client()
|
|
|
|
else:
|
|
|
|
usage()
|
1991-07-01 15:32:32 -03:00
|
|
|
|
|
|
|
def usage():
|
2004-07-18 02:56:09 -03:00
|
|
|
sys.stdout = sys.stderr
|
2007-07-17 17:59:35 -03:00
|
|
|
print('Usage: udpecho -s [port] (server)')
|
|
|
|
print('or: udpecho -c host [port] <file (client)')
|
2004-07-18 02:56:09 -03:00
|
|
|
sys.exit(2)
|
1991-07-01 15:32:32 -03:00
|
|
|
|
|
|
|
def server():
|
2004-07-18 02:56:09 -03:00
|
|
|
if len(sys.argv) > 2:
|
|
|
|
port = eval(sys.argv[2])
|
|
|
|
else:
|
|
|
|
port = ECHO_PORT
|
|
|
|
s = socket(AF_INET, SOCK_DGRAM)
|
|
|
|
s.bind(('', port))
|
2007-07-17 17:59:35 -03:00
|
|
|
print('udp echo server ready')
|
2004-07-18 02:56:09 -03:00
|
|
|
while 1:
|
|
|
|
data, addr = s.recvfrom(BUFSIZE)
|
2007-07-17 17:59:35 -03:00
|
|
|
print('server received %r from %r' % (data, addr))
|
2004-07-18 02:56:09 -03:00
|
|
|
s.sendto(data, addr)
|
1991-07-01 15:32:32 -03:00
|
|
|
|
|
|
|
def client():
|
2004-07-18 02:56:09 -03:00
|
|
|
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))
|
2007-07-17 17:59:35 -03:00
|
|
|
print('udp echo client ready, reading stdin')
|
2004-07-18 02:56:09 -03:00
|
|
|
while 1:
|
|
|
|
line = sys.stdin.readline()
|
|
|
|
if not line:
|
|
|
|
break
|
|
|
|
s.sendto(line, addr)
|
|
|
|
data, fromaddr = s.recvfrom(BUFSIZE)
|
2007-07-17 17:59:35 -03:00
|
|
|
print('client received %r from %r' % (data, fromaddr))
|
1991-07-01 15:32:32 -03:00
|
|
|
|
|
|
|
main()
|