[Python-checkins] python/dist/src/Demo/sockets broadcast.py, 1.5, 1.6 echosvr.py, 1.7, 1.8 finger.py, 1.5, 1.6 ftp.py, 1.6, 1.7 gopher.py, 1.5, 1.6 mcast.py, 1.10, 1.11 radio.py, 1.4, 1.5 rpython.py, 1.2, 1.3 rpythond.py, 1.3, 1.4 telnet.py, 1.6, 1.7 throughput.py, 1.6, 1.7 udpecho.py, 1.6, 1.7 unicast.py, 1.2, 1.3 unixserver.py, 1.3, 1.4

tim_one at users.sourceforge.net tim_one at users.sourceforge.net
Sun Jul 18 07:56:27 CEST 2004


Update of /cvsroot/python/python/dist/src/Demo/sockets
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv28702/Demo/sockets
Modified Files:
	broadcast.py echosvr.py finger.py ftp.py gopher.py mcast.py 
	radio.py rpython.py rpythond.py telnet.py throughput.py 
	udpecho.py unicast.py unixserver.py 
Log Message:
Whitespace normalization. Ran reindent.py over the entire source tree.
Index: broadcast.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/broadcast.py,v
retrieving revision 1.5
retrieving revision 1.6
diff -C2 -d -r1.5 -r1.6
*** broadcast.py	12 Feb 2004 17:35:03 -0000	1.5
--- broadcast.py	18 Jul 2004 05:56:09 -0000	1.6
***************
*** 11,17 ****
 
 while 1:
! 	data = repr(time.time()) + '\n'
! 	s.sendto(data, ('<broadcast>', MYPORT))
! 	time.sleep(2)
! 
! 	
--- 11,15 ----
 
 while 1:
! data = repr(time.time()) + '\n'
! s.sendto(data, ('<broadcast>', MYPORT))
! time.sleep(2)
Index: echosvr.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/echosvr.py,v
retrieving revision 1.7
retrieving revision 1.8
diff -C2 -d -r1.7 -r1.8
*** echosvr.py	25 Aug 2000 16:03:27 -0000	1.7
--- echosvr.py	18 Jul 2004 05:56:09 -0000	1.8
***************
*** 14,31 ****
 
 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)
 
 main()
--- 14,31 ----
 
 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)
 
 main()
Index: finger.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/finger.py,v
retrieving revision 1.5
retrieving revision 1.6
diff -C2 -d -r1.5 -r1.6
*** finger.py	25 Aug 2000 15:38:41 -0000	1.5
--- finger.py	18 Jul 2004 05:56:09 -0000	1.6
***************
*** 23,34 ****
 #
 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()
 
 
--- 23,34 ----
 #
 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()
 
 
***************
*** 36,55 ****
 #
 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)
 
 
--- 36,55 ----
 #
 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)
 
 
Index: ftp.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/ftp.py,v
retrieving revision 1.6
retrieving revision 1.7
diff -C2 -d -r1.6 -r1.7
*** ftp.py	12 Feb 2004 17:35:03 -0000	1.6
--- ftp.py	18 Jul 2004 05:56:09 -0000	1.7
***************
*** 38,43 ****
 #
 def main():
! 	hostname = sys.argv[1]
! 	control(hostname)
 
 
--- 38,43 ----
 #
 def main():
! hostname = sys.argv[1]
! control(hostname)
 
 
***************
*** 45,70 ****
 #
 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')
 
 
--- 45,70 ----
 #
 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')
 
 
***************
*** 76,87 ****
 #
 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
 
 
--- 76,87 ----
 #
 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
 
 
***************
*** 89,100 ****
 #
 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)
 
 
--- 89,100 ----
 #
 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)
 
 
***************
*** 106,120 ****
 #
 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
 
 
--- 106,120 ----
 #
 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
 
 
***************
*** 122,143 ****
 #
 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)'
 
 # Get a command from the user.
 #
 def getcommand():
! 	try:
! 		while 1:
! 			line = raw_input('ftp.py> ')
! 			if line: return line
! 	except EOFError:
! 		return ''
 
 
--- 122,143 ----
 #
 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)'
 
 # Get a command from the user.
 #
 def getcommand():
! try:
! while 1:
! line = raw_input('ftp.py> ')
! if line: return line
! except EOFError:
! return ''
 
 
Index: gopher.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/gopher.py,v
retrieving revision 1.5
retrieving revision 1.6
diff -C2 -d -r1.5 -r1.6
*** gopher.py	12 Feb 2004 17:35:03 -0000	1.5
--- gopher.py	18 Jul 2004 05:56:09 -0000	1.6
***************
*** 31,36 ****
 # 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>'}
 
 # Oft-used characters and strings
--- 31,36 ----
 # 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>'}
 
 # Oft-used characters and strings
***************
*** 40,128 ****
 # 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
 
 # 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')
 
 # 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
 
 # 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
 
 # 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()
 
 # 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
 
 # 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)
 
 # A *very* simple interactive browser
--- 40,128 ----
 # 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
 
 # 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')
 
 # 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
 
 # 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
 
 # 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()
 
 # 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
 
 # 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)
 
 # A *very* simple interactive browser
***************
*** 130,346 ****
 # 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]'
 
 # 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'
 
 # 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()
 
 # 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)
 
 # "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
 
 # "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()
 
 # "Browse" a sound file, i.e. play it or save it
 def browse_sound(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}
 
 # 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
 
 # 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
 
 # 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
 
 # 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()
 
 # Call the test program as a main program
--- 130,346 ----
 # 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]'
 
 # 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'
 
 # 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()
 
 # 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)
 
 # "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
 
 # "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()
 
 # "Browse" a sound file, i.e. play it or save it
 def browse_sound(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}
 
 # 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
 
 # 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
 
 # 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
 
 # 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()
 
 # Call the test program as a main program
Index: mcast.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/mcast.py,v
retrieving revision 1.10
retrieving revision 1.11
diff -C2 -d -r1.10 -r1.11
*** mcast.py	12 Feb 2004 17:35:03 -0000	1.10
--- mcast.py	18 Jul 2004 05:56:09 -0000	1.11
***************
*** 20,93 ****
 # Main program
 def main():
! 	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)
 
 
 # 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 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
 
 
--- 20,93 ----
 # Main program
 def main():
! 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)
 
 
 # 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 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
 
 
Index: radio.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/radio.py,v
retrieving revision 1.4
retrieving revision 1.5
diff -C2 -d -r1.4 -r1.5
*** radio.py	12 Feb 2004 17:35:03 -0000	1.4
--- radio.py	18 Jul 2004 05:56:09 -0000	1.5
***************
*** 10,14 ****
 
 while 1:
! 	data, wherefrom = s.recvfrom(1500, 0)
! 	sys.stderr.write(repr(wherefrom) + '\n')
! 	sys.stdout.write(data)
--- 10,14 ----
 
 while 1:
! data, wherefrom = s.recvfrom(1500, 0)
! sys.stderr.write(repr(wherefrom) + '\n')
! sys.stdout.write(data)
Index: rpython.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/rpython.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -C2 -d -r1.2 -r1.3
*** rpython.py	27 Nov 1996 19:50:43 -0000	1.2
--- rpython.py	18 Jul 2004 05:56:09 -0000	1.3
***************
*** 12,35 ****
 
 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,
 
 main()
--- 12,35 ----
 
 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,
 
 main()
Index: rpythond.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/rpythond.py,v
retrieving revision 1.3
retrieving revision 1.4
diff -C2 -d -r1.3 -r1.4
*** rpythond.py	25 Aug 2000 15:38:41 -0000	1.3
--- rpythond.py	18 Jul 2004 05:56:09 -0000	1.4
***************
*** 15,52 ****
 
 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()
 
 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()
 
 main()
--- 15,52 ----
 
 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()
 
 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()
 
 main()
Index: telnet.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/telnet.py,v
retrieving revision 1.6
retrieving revision 1.7
diff -C2 -d -r1.6 -r1.7
*** telnet.py	12 Feb 2004 17:35:03 -0000	1.6
--- telnet.py	18 Jul 2004 05:56:09 -0000	1.7
***************
*** 21,25 ****
 # Telnet protocol characters
 
! IAC = chr(255)	# Interpret as command
 DONT = chr(254)
 DO = chr(253)
--- 21,25 ----
 # Telnet protocol characters
 
! IAC = chr(255) # Interpret as command
 DONT = chr(254)
 DO = chr(253)
***************
*** 28,109 ****
 
 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()
 
 
 try:
! 	main()
 except KeyboardInterrupt:
! 	pass
--- 28,109 ----
 
 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()
 
 
 try:
! main()
 except KeyboardInterrupt:
! pass
Index: throughput.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/throughput.py,v
retrieving revision 1.6
retrieving revision 1.7
diff -C2 -d -r1.6 -r1.7
*** throughput.py	25 Aug 2000 15:38:41 -0000	1.6
--- throughput.py	18 Jul 2004 05:56:09 -0000	1.7
***************
*** 4,9 ****
 #
 # Usage:
! # 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.
--- 4,9 ----
 #
 # Usage:
! # 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.
***************
*** 22,92 ****
 
 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: (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
 
 
 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.'
 
 
--- 22,92 ----
 
 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: (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
 
 
 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.'
 
 
Index: udpecho.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/sockets/udpecho.py,v
retrieving revision 1.6
retrieving revision 1.7
diff -C2 -d -r1.6 -r1.7
*** udpecho.py	12 Feb 2004 17:35:03 -0000	1.6
--- udpecho.py	18 Jul 2004 05:56:09 -0000	1.7
***************
*** 13,63 ****
 
 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 %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)
 
 main()
--- 13,63 ----
 
 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 %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)
 
 main()


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /