summaryrefslogtreecommitdiffstats
path: root/Demo/sockets
diff options
context:
space:
mode:
authorTim Peters <tim.peters@gmail.com>2004-07-18 05:56:09 (GMT)
committerTim Peters <tim.peters@gmail.com>2004-07-18 05:56:09 (GMT)
commite6ddc8b20b493fef2e7cffb2e1351fe1d238857e (patch)
tree3b3d8fcd92e1d8f0cad44297d5c2ae8522bb984c /Demo/sockets
parent4fba4521e836e0cab08316592392b1e4d06eb6ef (diff)
downloadcpython-e6ddc8b20b493fef2e7cffb2e1351fe1d238857e.zip
cpython-e6ddc8b20b493fef2e7cffb2e1351fe1d238857e.tar.gz
cpython-e6ddc8b20b493fef2e7cffb2e1351fe1d238857e.tar.bz2
Whitespace normalization. Ran reindent.py over the entire source tree.
Diffstat (limited to 'Demo/sockets')
-rwxr-xr-xDemo/sockets/broadcast.py8
-rwxr-xr-xDemo/sockets/echosvr.py28
-rwxr-xr-xDemo/sockets/finger.py48
-rwxr-xr-xDemo/sockets/ftp.py130
-rwxr-xr-xDemo/sockets/gopher.py498
-rwxr-xr-xDemo/sockets/mcast.py116
-rwxr-xr-xDemo/sockets/radio.py6
-rwxr-xr-xDemo/sockets/rpython.py40
-rwxr-xr-xDemo/sockets/rpythond.py64
-rwxr-xr-xDemo/sockets/telnet.py154
-rwxr-xr-xDemo/sockets/throughput.py120
-rwxr-xr-xDemo/sockets/udpecho.py82
-rw-r--r--Demo/sockets/unicast.py8
-rw-r--r--Demo/sockets/unixserver.py2
14 files changed, 650 insertions, 654 deletions
diff --git a/Demo/sockets/broadcast.py b/Demo/sockets/broadcast.py
index 010162c..6d2b1e8 100755
--- a/Demo/sockets/broadcast.py
+++ b/Demo/sockets/broadcast.py
@@ -10,8 +10,6 @@ s.bind(('', 0))
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
while 1:
- data = repr(time.time()) + '\n'
- s.sendto(data, ('<broadcast>', MYPORT))
- time.sleep(2)
-
-
+ data = repr(time.time()) + '\n'
+ s.sendto(data, ('<broadcast>', MYPORT))
+ time.sleep(2)
diff --git a/Demo/sockets/echosvr.py b/Demo/sockets/echosvr.py
index a37f9c2..f8a9623 100755
--- a/Demo/sockets/echosvr.py
+++ b/Demo/sockets/echosvr.py
@@ -13,19 +13,19 @@ ECHO_PORT = 50000 + 7
BUFSIZE = 1024
def main():
- if len(sys.argv) > 1:
- port = int(eval(sys.argv[1]))
- else:
- port = ECHO_PORT
- s = socket(AF_INET, SOCK_STREAM)
- s.bind(('', port))
- s.listen(1)
- conn, (remotehost, remoteport) = s.accept()
- print 'connected by', remotehost, remoteport
- while 1:
- data = conn.recv(BUFSIZE)
- if not data:
- break
- conn.send(data)
+ if len(sys.argv) > 1:
+ port = int(eval(sys.argv[1]))
+ else:
+ port = ECHO_PORT
+ s = socket(AF_INET, SOCK_STREAM)
+ s.bind(('', port))
+ s.listen(1)
+ conn, (remotehost, remoteport) = s.accept()
+ print 'connected by', remotehost, remoteport
+ while 1:
+ data = conn.recv(BUFSIZE)
+ if not data:
+ break
+ conn.send(data)
main()
diff --git a/Demo/sockets/finger.py b/Demo/sockets/finger.py
index 0c2baed..e8b9ed2 100755
--- a/Demo/sockets/finger.py
+++ b/Demo/sockets/finger.py
@@ -22,35 +22,35 @@ FINGER_PORT = 79
# Output goes directly to stdout (although this can be changed).
#
def finger(host, args):
- s = socket(AF_INET, SOCK_STREAM)
- s.connect((host, FINGER_PORT))
- s.send(args + '\n')
- while 1:
- buf = s.recv(1024)
- if not buf: break
- sys.stdout.write(buf)
- sys.stdout.flush()
+ s = socket(AF_INET, SOCK_STREAM)
+ s.connect((host, FINGER_PORT))
+ s.send(args + '\n')
+ while 1:
+ buf = s.recv(1024)
+ if not buf: break
+ sys.stdout.write(buf)
+ sys.stdout.flush()
# Main function: argument parsing.
#
def main():
- options = ''
- i = 1
- while i < len(sys.argv) and sys.argv[i][:1] == '-':
- options = options + sys.argv[i] + ' '
- i = i+1
- args = sys.argv[i:]
- if not args:
- args = ['']
- for arg in args:
- if '@' in arg:
- at = string.index(arg, '@')
- host = arg[at+1:]
- arg = arg[:at]
- else:
- host = ''
- finger(host, options + arg)
+ options = ''
+ i = 1
+ while i < len(sys.argv) and sys.argv[i][:1] == '-':
+ options = options + sys.argv[i] + ' '
+ i = i+1
+ args = sys.argv[i:]
+ if not args:
+ args = ['']
+ for arg in args:
+ if '@' in arg:
+ at = string.index(arg, '@')
+ host = arg[at+1:]
+ arg = arg[:at]
+ else:
+ host = ''
+ finger(host, options + arg)
# Call the main function.
diff --git a/Demo/sockets/ftp.py b/Demo/sockets/ftp.py
index 9e1d5a1..6e9282a 100755
--- a/Demo/sockets/ftp.py
+++ b/Demo/sockets/ftp.py
@@ -37,35 +37,35 @@ FTP_DATA_PORT = FTP_DATA_PORT + 50000
# Main program (called at the end of this file).
#
def main():
- hostname = sys.argv[1]
- control(hostname)
+ hostname = sys.argv[1]
+ control(hostname)
# Control process (user interface and user protocol interpreter).
#
def control(hostname):
- #
- # Create control connection
- #
- s = socket(AF_INET, SOCK_STREAM)
- s.connect((hostname, FTP_PORT))
- f = s.makefile('r') # Reading the replies is easier from a file...
- #
- # Control loop
- #
- r = None
- while 1:
- code = getreply(f)
- if code in ('221', 'EOF'): break
- if code == '150':
- getdata(r)
- code = getreply(f)
- r = None
- if not r:
- r = newdataport(s, f)
- cmd = getcommand()
- if not cmd: break
- s.send(cmd + '\r\n')
+ #
+ # Create control connection
+ #
+ s = socket(AF_INET, SOCK_STREAM)
+ s.connect((hostname, FTP_PORT))
+ f = s.makefile('r') # Reading the replies is easier from a file...
+ #
+ # Control loop
+ #
+ r = None
+ while 1:
+ code = getreply(f)
+ if code in ('221', 'EOF'): break
+ if code == '150':
+ getdata(r)
+ code = getreply(f)
+ r = None
+ if not r:
+ r = newdataport(s, f)
+ cmd = getcommand()
+ if not cmd: break
+ s.send(cmd + '\r\n')
# Create a new data port and send a PORT command to the server for it.
@@ -75,27 +75,27 @@ def control(hostname):
nextport = 0
#
def newdataport(s, f):
- global nextport
- port = nextport + FTP_DATA_PORT
- nextport = (nextport+1) % 16
- r = socket(AF_INET, SOCK_STREAM)
- r.bind((gethostbyname(gethostname()), port))
- r.listen(1)
- sendportcmd(s, f, port)
- return r
+ global nextport
+ port = nextport + FTP_DATA_PORT
+ nextport = (nextport+1) % 16
+ r = socket(AF_INET, SOCK_STREAM)
+ r.bind((gethostbyname(gethostname()), port))
+ r.listen(1)
+ sendportcmd(s, f, port)
+ return r
# Send an appropriate port command.
#
def sendportcmd(s, f, port):
- hostname = gethostname()
- hostaddr = gethostbyname(hostname)
- hbytes = string.splitfields(hostaddr, '.')
- pbytes = [repr(port/256), repr(port%256)]
- bytes = hbytes + pbytes
- cmd = 'PORT ' + string.joinfields(bytes, ',')
- s.send(cmd + '\r\n')
- code = getreply(f)
+ hostname = gethostname()
+ hostaddr = gethostbyname(hostname)
+ hbytes = string.splitfields(hostaddr, '.')
+ pbytes = [repr(port/256), repr(port%256)]
+ bytes = hbytes + pbytes
+ cmd = 'PORT ' + string.joinfields(bytes, ',')
+ s.send(cmd + '\r\n')
+ code = getreply(f)
# Process an ftp reply and return the 3-digit reply code (as a string).
@@ -105,40 +105,40 @@ def sendportcmd(s, f, port):
# Any text while receiving the reply is echoed to the file.
#
def getreply(f):
- line = f.readline()
- if not line: return 'EOF'
- print line,
- code = line[:3]
- if line[3:4] == '-':
- while 1:
- line = f.readline()
- if not line: break # Really an error
- print line,
- if line[:3] == code and line[3:4] != '-': break
- return code
+ line = f.readline()
+ if not line: return 'EOF'
+ print line,
+ code = line[:3]
+ if line[3:4] == '-':
+ while 1:
+ line = f.readline()
+ if not line: break # Really an error
+ print line,
+ if line[:3] == code and line[3:4] != '-': break
+ return code
# Get the data from the data connection.
#
def getdata(r):
- print '(accepting data connection)'
- conn, host = r.accept()
- print '(data connection accepted)'
- while 1:
- data = conn.recv(BUFSIZE)
- if not data: break
- sys.stdout.write(data)
- print '(end of data connection)'
+ print '(accepting data connection)'
+ conn, host = r.accept()
+ print '(data connection accepted)'
+ while 1:
+ data = conn.recv(BUFSIZE)
+ if not data: break
+ sys.stdout.write(data)
+ print '(end of data connection)'
# Get a command from the user.
#
def getcommand():
- try:
- while 1:
- line = raw_input('ftp.py> ')
- if line: return line
- except EOFError:
- return ''
+ try:
+ while 1:
+ line = raw_input('ftp.py> ')
+ if line: return line
+ except EOFError:
+ return ''
# Call the main program.
diff --git a/Demo/sockets/gopher.py b/Demo/sockets/gopher.py
index 4e1cb30..cd76659 100755
--- a/Demo/sockets/gopher.py
+++ b/Demo/sockets/gopher.py
@@ -30,8 +30,8 @@ T_SOUND = 's'
# Dictionary mapping types to strings
typename = {'0': '<TEXT>', '1': '<DIR>', '2': '<CSO>', '3': '<ERROR>', \
- '4': '<BINHEX>', '5': '<DOS>', '6': '<UUENCODE>', '7': '<SEARCH>', \
- '8': '<TELNET>', '9': '<BINARY>', '+': '<REDUNDANT>', 's': '<SOUND>'}
+ '4': '<BINHEX>', '5': '<DOS>', '6': '<UUENCODE>', '7': '<SEARCH>', \
+ '8': '<TELNET>', '9': '<BINARY>', '+': '<REDUNDANT>', 's': '<SOUND>'}
# Oft-used characters and strings
CRLF = '\r\n'
@@ -39,309 +39,309 @@ TAB = '\t'
# Open a TCP connection to a given host and port
def open_socket(host, port):
- if not port:
- port = DEF_PORT
- elif type(port) == type(''):
- port = string.atoi(port)
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.connect((host, port))
- return s
+ if not port:
+ port = DEF_PORT
+ elif type(port) == type(''):
+ port = string.atoi(port)
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.connect((host, port))
+ return s
# Send a selector to a given host and port, return a file with the reply
def send_request(selector, host, port):
- s = open_socket(host, port)
- s.send(selector + CRLF)
- s.shutdown(1)
- return s.makefile('r')
+ s = open_socket(host, port)
+ s.send(selector + CRLF)
+ s.shutdown(1)
+ return s.makefile('r')
# Get a menu in the form of a list of entries
def get_menu(selector, host, port):
- f = send_request(selector, host, port)
- list = []
- while 1:
- line = f.readline()
- if not line:
- print '(Unexpected EOF from server)'
- break
- if line[-2:] == CRLF:
- line = line[:-2]
- elif line[-1:] in CRLF:
- line = line[:-1]
- if line == '.':
- break
- if not line:
- print '(Empty line from server)'
- continue
- typechar = line[0]
- parts = string.splitfields(line[1:], TAB)
- if len(parts) < 4:
- print '(Bad line from server: %r)' % (line,)
- continue
- if len(parts) > 4:
- print '(Extra info from server: %r)' % (parts[4:],)
- parts.insert(0, typechar)
- list.append(parts)
- f.close()
- return list
+ f = send_request(selector, host, port)
+ list = []
+ while 1:
+ line = f.readline()
+ if not line:
+ print '(Unexpected EOF from server)'
+ break
+ if line[-2:] == CRLF:
+ line = line[:-2]
+ elif line[-1:] in CRLF:
+ line = line[:-1]
+ if line == '.':
+ break
+ if not line:
+ print '(Empty line from server)'
+ continue
+ typechar = line[0]
+ parts = string.splitfields(line[1:], TAB)
+ if len(parts) < 4:
+ print '(Bad line from server: %r)' % (line,)
+ continue
+ if len(parts) > 4:
+ print '(Extra info from server: %r)' % (parts[4:],)
+ parts.insert(0, typechar)
+ list.append(parts)
+ f.close()
+ return list
# Get a text file as a list of lines, with trailing CRLF stripped
def get_textfile(selector, host, port):
- list = []
- get_alt_textfile(selector, host, port, list.append)
- return list
+ list = []
+ get_alt_textfile(selector, host, port, list.append)
+ return list
# Get a text file and pass each line to a function, with trailing CRLF stripped
def get_alt_textfile(selector, host, port, func):
- f = send_request(selector, host, port)
- while 1:
- line = f.readline()
- if not line:
- print '(Unexpected EOF from server)'
- break
- if line[-2:] == CRLF:
- line = line[:-2]
- elif line[-1:] in CRLF:
- line = line[:-1]
- if line == '.':
- break
- if line[:2] == '..':
- line = line[1:]
- func(line)
- f.close()
+ f = send_request(selector, host, port)
+ while 1:
+ line = f.readline()
+ if not line:
+ print '(Unexpected EOF from server)'
+ break
+ if line[-2:] == CRLF:
+ line = line[:-2]
+ elif line[-1:] in CRLF:
+ line = line[:-1]
+ if line == '.':
+ break
+ if line[:2] == '..':
+ line = line[1:]
+ func(line)
+ f.close()
# Get a binary file as one solid data block
def get_binary(selector, host, port):
- f = send_request(selector, host, port)
- data = f.read()
- f.close()
- return data
+ f = send_request(selector, host, port)
+ data = f.read()
+ f.close()
+ return data
# Get a binary file and pass each block to a function
def get_alt_binary(selector, host, port, func, blocksize):
- f = send_request(selector, host, port)
- while 1:
- data = f.read(blocksize)
- if not data:
- break
- func(data)
+ f = send_request(selector, host, port)
+ while 1:
+ data = f.read(blocksize)
+ if not data:
+ break
+ func(data)
# A *very* simple interactive browser
# Browser main command, has default arguments
def browser(*args):
- selector = DEF_SELECTOR
- host = DEF_HOST
- port = DEF_PORT
- n = len(args)
- if n > 0 and args[0]:
- selector = args[0]
- if n > 1 and args[1]:
- host = args[1]
- if n > 2 and args[2]:
- port = args[2]
- if n > 3:
- raise RuntimeError, 'too many args'
- try:
- browse_menu(selector, host, port)
- except socket.error, msg:
- print 'Socket error:', msg
- sys.exit(1)
- except KeyboardInterrupt:
- print '\n[Goodbye]'
+ selector = DEF_SELECTOR
+ host = DEF_HOST
+ port = DEF_PORT
+ n = len(args)
+ if n > 0 and args[0]:
+ selector = args[0]
+ if n > 1 and args[1]:
+ host = args[1]
+ if n > 2 and args[2]:
+ port = args[2]
+ if n > 3:
+ raise RuntimeError, 'too many args'
+ try:
+ browse_menu(selector, host, port)
+ except socket.error, msg:
+ print 'Socket error:', msg
+ sys.exit(1)
+ except KeyboardInterrupt:
+ print '\n[Goodbye]'
# Browse a menu
def browse_menu(selector, host, port):
- list = get_menu(selector, host, port)
- while 1:
- print '----- MENU -----'
- print 'Selector:', repr(selector)
- print 'Host:', host, ' Port:', port
- print
- for i in range(len(list)):
- item = list[i]
- typechar, description = item[0], item[1]
- print string.rjust(repr(i+1), 3) + ':', description,
- if typename.has_key(typechar):
- print typename[typechar]
- else:
- print '<TYPE=' + repr(typechar) + '>'
- print
- while 1:
- try:
- str = raw_input('Choice [CR == up a level]: ')
- except EOFError:
- print
- return
- if not str:
- return
- try:
- choice = string.atoi(str)
- except string.atoi_error:
- print 'Choice must be a number; try again:'
- continue
- if not 0 < choice <= len(list):
- print 'Choice out of range; try again:'
- continue
- break
- item = list[choice-1]
- typechar = item[0]
- [i_selector, i_host, i_port] = item[2:5]
- if typebrowser.has_key(typechar):
- browserfunc = typebrowser[typechar]
- try:
- browserfunc(i_selector, i_host, i_port)
- except (IOError, socket.error):
- print '***', sys.exc_type, ':', sys.exc_value
- else:
- print 'Unsupported object type'
+ list = get_menu(selector, host, port)
+ while 1:
+ print '----- MENU -----'
+ print 'Selector:', repr(selector)
+ print 'Host:', host, ' Port:', port
+ print
+ for i in range(len(list)):
+ item = list[i]
+ typechar, description = item[0], item[1]
+ print string.rjust(repr(i+1), 3) + ':', description,
+ if typename.has_key(typechar):
+ print typename[typechar]
+ else:
+ print '<TYPE=' + repr(typechar) + '>'
+ print
+ while 1:
+ try:
+ str = raw_input('Choice [CR == up a level]: ')
+ except EOFError:
+ print
+ return
+ if not str:
+ return
+ try:
+ choice = string.atoi(str)
+ except string.atoi_error:
+ print 'Choice must be a number; try again:'
+ continue
+ if not 0 < choice <= len(list):
+ print 'Choice out of range; try again:'
+ continue
+ break
+ item = list[choice-1]
+ typechar = item[0]
+ [i_selector, i_host, i_port] = item[2:5]
+ if typebrowser.has_key(typechar):
+ browserfunc = typebrowser[typechar]
+ try:
+ browserfunc(i_selector, i_host, i_port)
+ except (IOError, socket.error):
+ print '***', sys.exc_type, ':', sys.exc_value
+ else:
+ print 'Unsupported object type'
# Browse a text file
def browse_textfile(selector, host, port):
- x = None
- try:
- p = os.popen('${PAGER-more}', 'w')
- x = SaveLines(p)
- get_alt_textfile(selector, host, port, x.writeln)
- except IOError, msg:
- print 'IOError:', msg
- if x:
- x.close()
- f = open_savefile()
- if not f:
- return
- x = SaveLines(f)
- try:
- get_alt_textfile(selector, host, port, x.writeln)
- print 'Done.'
- except IOError, msg:
- print 'IOError:', msg
- x.close()
+ x = None
+ try:
+ p = os.popen('${PAGER-more}', 'w')
+ x = SaveLines(p)
+ get_alt_textfile(selector, host, port, x.writeln)
+ except IOError, msg:
+ print 'IOError:', msg
+ if x:
+ x.close()
+ f = open_savefile()
+ if not f:
+ return
+ x = SaveLines(f)
+ try:
+ get_alt_textfile(selector, host, port, x.writeln)
+ print 'Done.'
+ except IOError, msg:
+ print 'IOError:', msg
+ x.close()
# Browse a search index
def browse_search(selector, host, port):
- while 1:
- print '----- SEARCH -----'
- print 'Selector:', repr(selector)
- print 'Host:', host, ' Port:', port
- print
- try:
- query = raw_input('Query [CR == up a level]: ')
- except EOFError:
- print
- break
- query = string.strip(query)
- if not query:
- break
- if '\t' in query:
- print 'Sorry, queries cannot contain tabs'
- continue
- browse_menu(selector + TAB + query, host, port)
+ while 1:
+ print '----- SEARCH -----'
+ print 'Selector:', repr(selector)
+ print 'Host:', host, ' Port:', port
+ print
+ try:
+ query = raw_input('Query [CR == up a level]: ')
+ except EOFError:
+ print
+ break
+ query = string.strip(query)
+ if not query:
+ break
+ if '\t' in query:
+ print 'Sorry, queries cannot contain tabs'
+ continue
+ browse_menu(selector + TAB + query, host, port)
# "Browse" telnet-based information, i.e. open a telnet session
def browse_telnet(selector, host, port):
- if selector:
- print 'Log in as', repr(selector)
- if type(port) <> type(''):
- port = repr(port)
- sts = os.system('set -x; exec telnet ' + host + ' ' + port)
- if sts:
- print 'Exit status:', sts
+ if selector:
+ print 'Log in as', repr(selector)
+ if type(port) <> type(''):
+ port = repr(port)
+ sts = os.system('set -x; exec telnet ' + host + ' ' + port)
+ if sts:
+ print 'Exit status:', sts
# "Browse" a binary file, i.e. save it to a file
def browse_binary(selector, host, port):
- f = open_savefile()
- if not f:
- return
- x = SaveWithProgress(f)
- get_alt_binary(selector, host, port, x.write, 8*1024)
- x.close()
+ f = open_savefile()
+ if not f:
+ return
+ x = SaveWithProgress(f)
+ get_alt_binary(selector, host, port, x.write, 8*1024)
+ x.close()
# "Browse" a sound file, i.e. play it or save it
def browse_sound(selector, host, port):
- browse_binary(selector, host, port)
+ browse_binary(selector, host, port)
# Dictionary mapping types to browser functions
typebrowser = {'0': browse_textfile, '1': browse_menu, \
- '4': browse_binary, '5': browse_binary, '6': browse_textfile, \
- '7': browse_search, \
- '8': browse_telnet, '9': browse_binary, 's': browse_sound}
+ '4': browse_binary, '5': browse_binary, '6': browse_textfile, \
+ '7': browse_search, \
+ '8': browse_telnet, '9': browse_binary, 's': browse_sound}
# Class used to save lines, appending a newline to each line
class SaveLines:
- def __init__(self, f):
- self.f = f
- def writeln(self, line):
- self.f.write(line + '\n')
- def close(self):
- sts = self.f.close()
- if sts:
- print 'Exit status:', sts
+ def __init__(self, f):
+ self.f = f
+ def writeln(self, line):
+ self.f.write(line + '\n')
+ def close(self):
+ sts = self.f.close()
+ if sts:
+ print 'Exit status:', sts
# Class used to save data while showing progress
class SaveWithProgress:
- def __init__(self, f):
- self.f = f
- def write(self, data):
- sys.stdout.write('#')
- sys.stdout.flush()
- self.f.write(data)
- def close(self):
- print
- sts = self.f.close()
- if sts:
- print 'Exit status:', sts
+ def __init__(self, f):
+ self.f = f
+ def write(self, data):
+ sys.stdout.write('#')
+ sys.stdout.flush()
+ self.f.write(data)
+ def close(self):
+ print
+ sts = self.f.close()
+ if sts:
+ print 'Exit status:', sts
# Ask for and open a save file, or return None if not to save
def open_savefile():
- try:
- savefile = raw_input( \
- 'Save as file [CR == don\'t save; |pipeline or ~user/... OK]: ')
- except EOFError:
- print
- return None
- savefile = string.strip(savefile)
- if not savefile:
- return None
- if savefile[0] == '|':
- cmd = string.strip(savefile[1:])
- try:
- p = os.popen(cmd, 'w')
- except IOError, msg:
- print repr(cmd), ':', msg
- return None
- print 'Piping through', repr(cmd), '...'
- return p
- if savefile[0] == '~':
- savefile = os.path.expanduser(savefile)
- try:
- f = open(savefile, 'w')
- except IOError, msg:
- print repr(savefile), ':', msg
- return None
- print 'Saving to', repr(savefile), '...'
- return f
+ try:
+ savefile = raw_input( \
+ 'Save as file [CR == don\'t save; |pipeline or ~user/... OK]: ')
+ except EOFError:
+ print
+ return None
+ savefile = string.strip(savefile)
+ if not savefile:
+ return None
+ if savefile[0] == '|':
+ cmd = string.strip(savefile[1:])
+ try:
+ p = os.popen(cmd, 'w')
+ except IOError, msg:
+ print repr(cmd), ':', msg
+ return None
+ print 'Piping through', repr(cmd), '...'
+ return p
+ if savefile[0] == '~':
+ savefile = os.path.expanduser(savefile)
+ try:
+ f = open(savefile, 'w')
+ except IOError, msg:
+ print repr(savefile), ':', msg
+ return None
+ print 'Saving to', repr(savefile), '...'
+ return f
# Test program
def test():
- if sys.argv[4:]:
- print 'usage: gopher [ [selector] host [port] ]'
- sys.exit(2)
- elif sys.argv[3:]:
- browser(sys.argv[1], sys.argv[2], sys.argv[3])
- elif sys.argv[2:]:
- try:
- port = string.atoi(sys.argv[2])
- selector = ''
- host = sys.argv[1]
- except string.atoi_error:
- selector = sys.argv[1]
- host = sys.argv[2]
- port = ''
- browser(selector, host, port)
- elif sys.argv[1:]:
- browser('', sys.argv[1])
- else:
- browser()
+ if sys.argv[4:]:
+ print 'usage: gopher [ [selector] host [port] ]'
+ sys.exit(2)
+ elif sys.argv[3:]:
+ browser(sys.argv[1], sys.argv[2], sys.argv[3])
+ elif sys.argv[2:]:
+ try:
+ port = string.atoi(sys.argv[2])
+ selector = ''
+ host = sys.argv[1]
+ except string.atoi_error:
+ selector = sys.argv[1]
+ host = sys.argv[2]
+ port = ''
+ browser(selector, host, port)
+ elif sys.argv[1:]:
+ browser('', sys.argv[1])
+ else:
+ browser()
# Call the test program as a main program
test()
diff --git a/Demo/sockets/mcast.py b/Demo/sockets/mcast.py
index 71bcc75..122dad7 100755
--- a/Demo/sockets/mcast.py
+++ b/Demo/sockets/mcast.py
@@ -19,76 +19,76 @@ from socket import *
# Main program
def main():
- flags = sys.argv[1:]
- #
- if flags:
- sender(flags[0])
- else:
- receiver()
+ flags = sys.argv[1:]
+ #
+ if flags:
+ sender(flags[0])
+ else:
+ receiver()
# Sender subroutine (only one per local area network)
def sender(flag):
- s = socket(AF_INET, SOCK_DGRAM)
- if flag == '-b':
- s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
- mygroup = '<broadcast>'
- else:
- mygroup = MYGROUP
- ttl = struct.pack('b', 1) # Time-to-live
- s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)
- while 1:
- data = repr(time.time())
-## data = data + (1400 - len(data)) * '\0'
- s.sendto(data, (mygroup, MYPORT))
- time.sleep(1)
+ s = socket(AF_INET, SOCK_DGRAM)
+ if flag == '-b':
+ s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
+ mygroup = '<broadcast>'
+ else:
+ mygroup = MYGROUP
+ ttl = struct.pack('b', 1) # Time-to-live
+ s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)
+ while 1:
+ data = repr(time.time())
+## data = data + (1400 - len(data)) * '\0'
+ s.sendto(data, (mygroup, MYPORT))
+ time.sleep(1)
# Receiver subroutine (as many as you like)
def receiver():
- # Open and initialize the socket
- s = openmcastsock(MYGROUP, MYPORT)
- #
- # Loop, printing any data we receive
- while 1:
- data, sender = s.recvfrom(1500)
- while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
- print sender, ':', repr(data)
+ # Open and initialize the socket
+ s = openmcastsock(MYGROUP, MYPORT)
+ #
+ # Loop, printing any data we receive
+ while 1:
+ data, sender = s.recvfrom(1500)
+ while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
+ print sender, ':', repr(data)
# Open a UDP socket, bind it to a port and select a multicast group
def openmcastsock(group, port):
- # Import modules used only here
- import string
- import struct
- #
- # Create a socket
- s = socket(AF_INET, SOCK_DGRAM)
- #
- # Allow multiple copies of this program on one machine
- # (not strictly needed)
- s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
- #
- # Bind it to the port
- s.bind(('', port))
- #
- # Look up multicast group address in name server
- # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
- group = gethostbyname(group)
- #
- # Construct binary group address
- bytes = map(int, string.split(group, "."))
- grpaddr = 0
- for byte in bytes: grpaddr = (grpaddr << 8) | byte
- #
- # Construct struct mreq from grpaddr and ifaddr
- ifaddr = INADDR_ANY
- mreq = struct.pack('ll', htonl(grpaddr), htonl(ifaddr))
- #
- # Add group membership
- s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)
- #
- return s
+ # Import modules used only here
+ import string
+ import struct
+ #
+ # Create a socket
+ s = socket(AF_INET, SOCK_DGRAM)
+ #
+ # Allow multiple copies of this program on one machine
+ # (not strictly needed)
+ s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
+ #
+ # Bind it to the port
+ s.bind(('', port))
+ #
+ # Look up multicast group address in name server
+ # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
+ group = gethostbyname(group)
+ #
+ # Construct binary group address
+ bytes = map(int, string.split(group, "."))
+ grpaddr = 0
+ for byte in bytes: grpaddr = (grpaddr << 8) | byte
+ #
+ # Construct struct mreq from grpaddr and ifaddr
+ ifaddr = INADDR_ANY
+ mreq = struct.pack('ll', htonl(grpaddr), htonl(ifaddr))
+ #
+ # Add group membership
+ s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)
+ #
+ return s
main()
diff --git a/Demo/sockets/radio.py b/Demo/sockets/radio.py
index b68a4ec..fa4ce75 100755
--- a/Demo/sockets/radio.py
+++ b/Demo/sockets/radio.py
@@ -9,6 +9,6 @@ s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', MYPORT))
while 1:
- data, wherefrom = s.recvfrom(1500, 0)
- sys.stderr.write(repr(wherefrom) + '\n')
- sys.stdout.write(data)
+ data, wherefrom = s.recvfrom(1500, 0)
+ sys.stderr.write(repr(wherefrom) + '\n')
+ sys.stdout.write(data)
diff --git a/Demo/sockets/rpython.py b/Demo/sockets/rpython.py
index 77b2a7a..8333d39 100755
--- a/Demo/sockets/rpython.py
+++ b/Demo/sockets/rpython.py
@@ -11,25 +11,25 @@ PORT = 4127
BUFSIZE = 1024
def main():
- if len(sys.argv) < 3:
- print "usage: rpython host command"
- sys.exit(2)
- host = sys.argv[1]
- port = PORT
- i = string.find(host, ':')
- if i >= 0:
- port = string.atoi(port[i+1:])
- host = host[:i]
- command = string.join(sys.argv[2:])
- s = socket(AF_INET, SOCK_STREAM)
- s.connect((host, port))
- s.send(command)
- s.shutdown(1)
- reply = ''
- while 1:
- data = s.recv(BUFSIZE)
- if not data: break
- reply = reply + data
- print reply,
+ if len(sys.argv) < 3:
+ print "usage: rpython host command"
+ sys.exit(2)
+ host = sys.argv[1]
+ port = PORT
+ i = string.find(host, ':')
+ if i >= 0:
+ port = string.atoi(port[i+1:])
+ host = host[:i]
+ command = string.join(sys.argv[2:])
+ s = socket(AF_INET, SOCK_STREAM)
+ s.connect((host, port))
+ s.send(command)
+ s.shutdown(1)
+ reply = ''
+ while 1:
+ data = s.recv(BUFSIZE)
+ if not data: break
+ reply = reply + data
+ print reply,
main()
diff --git a/Demo/sockets/rpythond.py b/Demo/sockets/rpythond.py
index 1109a99..81397d6 100755
--- a/Demo/sockets/rpythond.py
+++ b/Demo/sockets/rpythond.py
@@ -14,39 +14,39 @@ PORT = 4127
BUFSIZE = 1024
def main():
- if len(sys.argv) > 1:
- port = int(eval(sys.argv[1]))
- else:
- port = PORT
- s = socket(AF_INET, SOCK_STREAM)
- s.bind(('', port))
- s.listen(1)
- while 1:
- conn, (remotehost, remoteport) = s.accept()
- print 'connected by', remotehost, remoteport
- request = ''
- while 1:
- data = conn.recv(BUFSIZE)
- if not data:
- break
- request = request + data
- reply = execute(request)
- conn.send(reply)
- conn.close()
+ if len(sys.argv) > 1:
+ port = int(eval(sys.argv[1]))
+ else:
+ port = PORT
+ s = socket(AF_INET, SOCK_STREAM)
+ s.bind(('', port))
+ s.listen(1)
+ while 1:
+ conn, (remotehost, remoteport) = s.accept()
+ print 'connected by', remotehost, remoteport
+ request = ''
+ while 1:
+ data = conn.recv(BUFSIZE)
+ if not data:
+ break
+ request = request + data
+ reply = execute(request)
+ conn.send(reply)
+ conn.close()
def execute(request):
- stdout = sys.stdout
- stderr = sys.stderr
- sys.stdout = sys.stderr = fakefile = StringIO.StringIO()
- try:
- try:
- exec request in {}, {}
- except:
- print
- traceback.print_exc(100)
- finally:
- sys.stderr = stderr
- sys.stdout = stdout
- return fakefile.getvalue()
+ stdout = sys.stdout
+ stderr = sys.stderr
+ sys.stdout = sys.stderr = fakefile = StringIO.StringIO()
+ try:
+ try:
+ exec request in {}, {}
+ except:
+ print
+ traceback.print_exc(100)
+ finally:
+ sys.stderr = stderr
+ sys.stdout = stdout
+ return fakefile.getvalue()
main()
diff --git a/Demo/sockets/telnet.py b/Demo/sockets/telnet.py
index d86cbeb..d50c37f 100755
--- a/Demo/sockets/telnet.py
+++ b/Demo/sockets/telnet.py
@@ -20,90 +20,90 @@ BUFSIZE = 1024
# Telnet protocol characters
-IAC = chr(255) # Interpret as command
+IAC = chr(255) # Interpret as command
DONT = chr(254)
DO = chr(253)
WONT = chr(252)
WILL = chr(251)
def main():
- host = sys.argv[1]
- try:
- hostaddr = gethostbyname(host)
- except error:
- sys.stderr.write(sys.argv[1] + ': bad host name\n')
- sys.exit(2)
- #
- if len(sys.argv) > 2:
- servname = sys.argv[2]
- else:
- servname = 'telnet'
- #
- if '0' <= servname[:1] <= '9':
- port = eval(servname)
- else:
- try:
- port = getservbyname(servname, 'tcp')
- except error:
- sys.stderr.write(servname + ': bad tcp service name\n')
- sys.exit(2)
- #
- s = socket(AF_INET, SOCK_STREAM)
- #
- try:
- s.connect((host, port))
- except error, msg:
- sys.stderr.write('connect failed: ' + repr(msg) + '\n')
- sys.exit(1)
- #
- pid = posix.fork()
- #
- if pid == 0:
- # child -- read stdin, write socket
- while 1:
- line = sys.stdin.readline()
- s.send(line)
- else:
- # parent -- read socket, write stdout
- iac = 0 # Interpret next char as command
- opt = '' # Interpret next char as option
- while 1:
- data = s.recv(BUFSIZE)
- if not data:
- # EOF; kill child and exit
- sys.stderr.write( '(Closed by remote host)\n')
- posix.kill(pid, 9)
- sys.exit(1)
- cleandata = ''
- for c in data:
- if opt:
- print ord(c)
- s.send(opt + c)
- opt = ''
- elif iac:
- iac = 0
- if c == IAC:
- cleandata = cleandata + c
- elif c in (DO, DONT):
- if c == DO: print '(DO)',
- else: print '(DONT)',
- opt = IAC + WONT
- elif c in (WILL, WONT):
- if c == WILL: print '(WILL)',
- else: print '(WONT)',
- opt = IAC + DONT
- else:
- print '(command)', ord(c)
- elif c == IAC:
- iac = 1
- print '(IAC)',
- else:
- cleandata = cleandata + c
- sys.stdout.write(cleandata)
- sys.stdout.flush()
+ host = sys.argv[1]
+ try:
+ hostaddr = gethostbyname(host)
+ except error:
+ sys.stderr.write(sys.argv[1] + ': bad host name\n')
+ sys.exit(2)
+ #
+ if len(sys.argv) > 2:
+ servname = sys.argv[2]
+ else:
+ servname = 'telnet'
+ #
+ if '0' <= servname[:1] <= '9':
+ port = eval(servname)
+ else:
+ try:
+ port = getservbyname(servname, 'tcp')
+ except error:
+ sys.stderr.write(servname + ': bad tcp service name\n')
+ sys.exit(2)
+ #
+ s = socket(AF_INET, SOCK_STREAM)
+ #
+ try:
+ s.connect((host, port))
+ except error, msg:
+ sys.stderr.write('connect failed: ' + repr(msg) + '\n')
+ sys.exit(1)
+ #
+ pid = posix.fork()
+ #
+ if pid == 0:
+ # child -- read stdin, write socket
+ while 1:
+ line = sys.stdin.readline()
+ s.send(line)
+ else:
+ # parent -- read socket, write stdout
+ iac = 0 # Interpret next char as command
+ opt = '' # Interpret next char as option
+ while 1:
+ data = s.recv(BUFSIZE)
+ if not data:
+ # EOF; kill child and exit
+ sys.stderr.write( '(Closed by remote host)\n')
+ posix.kill(pid, 9)
+ sys.exit(1)
+ cleandata = ''
+ for c in data:
+ if opt:
+ print ord(c)
+ s.send(opt + c)
+ opt = ''
+ elif iac:
+ iac = 0
+ if c == IAC:
+ cleandata = cleandata + c
+ elif c in (DO, DONT):
+ if c == DO: print '(DO)',
+ else: print '(DONT)',
+ opt = IAC + WONT
+ elif c in (WILL, WONT):
+ if c == WILL: print '(WILL)',
+ else: print '(WONT)',
+ opt = IAC + DONT
+ else:
+ print '(command)', ord(c)
+ elif c == IAC:
+ iac = 1
+ print '(IAC)',
+ else:
+ cleandata = cleandata + c
+ sys.stdout.write(cleandata)
+ sys.stdout.flush()
try:
- main()
+ main()
except KeyboardInterrupt:
- pass
+ pass
diff --git a/Demo/sockets/throughput.py b/Demo/sockets/throughput.py
index fa250e7..b8df1f3 100755
--- a/Demo/sockets/throughput.py
+++ b/Demo/sockets/throughput.py
@@ -3,8 +3,8 @@
# Test network throughput.
#
# Usage:
-# 1) on host_A: throughput -s [port] # start a server
-# 2) on host_B: throughput -c count host_A [port] # start a client
+# 1) on host_A: throughput -s [port] # start a server
+# 2) on host_B: throughput -c count host_A [port] # start a client
#
# The server will service multiple clients until it is killed.
#
@@ -21,73 +21,73 @@ BUFSIZE = 1024
def main():
- if len(sys.argv) < 2:
- usage()
- if sys.argv[1] == '-s':
- server()
- elif sys.argv[1] == '-c':
- client()
- else:
- usage()
+ 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: (on host_A) throughput -s [port]'
- print 'and then: (on host_B) throughput -c count host_A [port]'
- sys.exit(2)
+ sys.stdout = sys.stderr
+ print 'Usage: (on host_A) throughput -s [port]'
+ print 'and then: (on host_B) throughput -c count host_A [port]'
+ sys.exit(2)
def server():
- if len(sys.argv) > 2:
- port = eval(sys.argv[2])
- else:
- port = MY_PORT
- s = socket(AF_INET, SOCK_STREAM)
- s.bind(('', port))
- s.listen(1)
- print 'Server ready...'
- while 1:
- conn, (host, remoteport) = s.accept()
- while 1:
- data = conn.recv(BUFSIZE)
- if not data:
- break
- del data
- conn.send('OK\n')
- conn.close()
- print 'Done with', host, 'port', remoteport
+ if len(sys.argv) > 2:
+ port = eval(sys.argv[2])
+ else:
+ port = MY_PORT
+ s = socket(AF_INET, SOCK_STREAM)
+ s.bind(('', port))
+ s.listen(1)
+ print 'Server ready...'
+ while 1:
+ conn, (host, remoteport) = s.accept()
+ while 1:
+ data = conn.recv(BUFSIZE)
+ if not data:
+ break
+ del data
+ conn.send('OK\n')
+ conn.close()
+ print 'Done with', host, 'port', remoteport
def client():
- if len(sys.argv) < 4:
- usage()
- count = int(eval(sys.argv[2]))
- host = sys.argv[3]
- if len(sys.argv) > 4:
- port = eval(sys.argv[4])
- else:
- port = MY_PORT
- testdata = 'x' * (BUFSIZE-1) + '\n'
- t1 = time.time()
- s = socket(AF_INET, SOCK_STREAM)
- t2 = time.time()
- s.connect((host, port))
- t3 = time.time()
- i = 0
- while i < count:
- i = i+1
- s.send(testdata)
- s.shutdown(1) # Send EOF
- t4 = time.time()
- data = s.recv(BUFSIZE)
- t5 = time.time()
- print data
- print 'Raw timers:', t1, t2, t3, t4, t5
- print 'Intervals:', t2-t1, t3-t2, t4-t3, t5-t4
- print 'Total:', t5-t1
- print 'Throughput:', round((BUFSIZE*count*0.001) / (t5-t1), 3),
- print 'K/sec.'
+ if len(sys.argv) < 4:
+ usage()
+ count = int(eval(sys.argv[2]))
+ host = sys.argv[3]
+ if len(sys.argv) > 4:
+ port = eval(sys.argv[4])
+ else:
+ port = MY_PORT
+ testdata = 'x' * (BUFSIZE-1) + '\n'
+ t1 = time.time()
+ s = socket(AF_INET, SOCK_STREAM)
+ t2 = time.time()
+ s.connect((host, port))
+ t3 = time.time()
+ i = 0
+ while i < count:
+ i = i+1
+ s.send(testdata)
+ s.shutdown(1) # Send EOF
+ t4 = time.time()
+ data = s.recv(BUFSIZE)
+ t5 = time.time()
+ print data
+ print 'Raw timers:', t1, t2, t3, t4, t5
+ print 'Intervals:', t2-t1, t3-t2, t4-t3, t5-t4
+ print 'Total:', t5-t1
+ print 'Throughput:', round((BUFSIZE*count*0.001) / (t5-t1), 3),
+ print 'K/sec.'
main()
diff --git a/Demo/sockets/udpecho.py b/Demo/sockets/udpecho.py
index 720cfe1..5181c82 100755
--- a/Demo/sockets/udpecho.py
+++ b/Demo/sockets/udpecho.py
@@ -12,52 +12,52 @@ 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()
+ 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)
+ 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 %r from %r' % (data, addr)
- s.sendto(data, addr)
+ 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 %r from %r' % (data, 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 %r from %r' % (data, fromaddr)
+ 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 %r from %r' % (data, fromaddr)
main()
diff --git a/Demo/sockets/unicast.py b/Demo/sockets/unicast.py
index 0a30f35..dd15e3c 100644
--- a/Demo/sockets/unicast.py
+++ b/Demo/sockets/unicast.py
@@ -9,8 +9,6 @@ s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', 0))
while 1:
- data = repr(time.time()) + '\n'
- s.sendto(data, ('', MYPORT))
- time.sleep(2)
-
-
+ data = repr(time.time()) + '\n'
+ s.sendto(data, ('', MYPORT))
+ time.sleep(2)
diff --git a/Demo/sockets/unixserver.py b/Demo/sockets/unixserver.py
index d4425f0..5eccabb 100644
--- a/Demo/sockets/unixserver.py
+++ b/Demo/sockets/unixserver.py
@@ -2,7 +2,7 @@
# Piet van Oostrum
import os
from socket import *
-FILE = 'blabla'
+FILE = 'blabla'
s = socket(AF_UNIX, SOCK_STREAM)
s.bind(FILE)
print 'Sock name is: ['+s.getsockname()+']'