[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
Tips on Using Remote Servers
Some of this chapter’s examples run server code on a remote computer. Though you
can also run the examples locally on localhost, remote execution better captures the
flexibility and power of sockets. To run remotely, you’ll need access to an Internet
accessible computer with Python, where you can upload and run scripts. You’ll also
need to be able to access the remote server from your PC. To help with this last step,
here are a few hints for readers new to using remote servers.
To transfer scripts to a remote machine, the FTP command is standard on Windows
machines and most others. On Windows, simply type it in a console window to connect
to an FTP server or start your favorite FTP client GUI program; on Linux, type the FTP
command in an xterm window. You’ll need to supply your account name and password
to connect to a nonanonymous FTP site. For anonymous FTP, use “anonymous” for
the username and your email address for the password.
To run scripts remotely from a command line, Telnet is a standard command on some
Unix-like machines, too. On Windows, it’s often run as a client GUI. For some server
machines, you’ll need to use SSH secure shell rather than Telnet to access a shell
prompt. There are a variety of SSH utilities available on the Web, including PuTTY,
used for this book. Python itself comes with a telnetlib telnet module, and a web
search will reveals current SSH options for Python scripts, including ssh.py, para-
miko, Twisted, Pexpect, and even subprocess.Popen.

Spawning Clients in Parallel


So far, we’ve run a server locally and remotely, and run individual clients manually,
one after another. Realistic servers are generally intended to handle many clients, of
course, and possibly at the same time. To see how our echo server handles the load,
let’s fire up eight copies of the client script in parallel using the script in Exam-
ple 12-3; see the end of Chapter 5 for details on the launchmodes module used here to
spawn clients and alternatives such as the multiprocessing and subprocess modules.


Example 12-3. PP4E\Internet\Sockets\testecho.py


import sys
from PP4E.launchmodes import QuietPortableLauncher


numclients = 8
def start(cmdline):
QuietPortableLauncher(cmdline, cmdline)()


start('echo-server.py') # spawn server locally if not yet started


args = ' '.join(sys.argv[1:]) # pass server name if running remotely
for i in range(numclients):
start('echo-client.py %s' % args) # spawn 8? clients to test the server


798 | Chapter 12: Network Scripting

Free download pdf