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

(yzsuai) #1

Running Socket Programs Locally


Let’s put this client and server to work. There are two ways to run these scripts—on
either the same machine or two different machines. To run the client and the server on
the same machine, bring up two command-line consoles on your computer, start the
server program in one, and run the client repeatedly in the other. The server keeps
running and responds to requests made each time you run the client script in the other
window.


For instance, here is the text that shows up in the MS-DOS console window where I’ve
started the server script:


C:\...\PP4E\Internet\Sockets> python echo-server.py
Server connected by ('127.0.0.1', 57666)
Server connected by ('127.0.0.1', 57667)
Server connected by ('127.0.0.1', 57668)

The output here gives the address (machine IP name and port number) of each con-
necting client. Like most servers, this one runs perpetually, listening for client connec-
tion requests. This server receives three, but I have to show you the client window’s
text for you to understand what this means:


C:\...\PP4E\Internet\Sockets> python echo-client.py
Client received: b'Echo=>Hello network world'

C:\...\PP4E\Internet\Sockets> python echo-client.py localhost spam Spam SPAM
Client received: b'Echo=>spam'
Client received: b'Echo=>Spam'
Client received: b'Echo=>SPAM'

C:\...\PP4E\Internet\Sockets> python echo-client.py localhost Shrubbery
Client received: b'Echo=>Shrubbery'

Here, I ran the client script three times, while the server script kept running in the other
window. Each client connected to the server, sent it a message of one or more lines of
text, and read back the server’s reply—an echo of each line of text sent from the client.
And each time a client is run, a new connection message shows up in the server’s
window (that’s why we got three). Because the server’s coded as an infinite loop, you
may need to kill it with Task Manager on Windows when you’re done testing, because
a Ctrl-C in the server’s console window is ignored; other platforms may fare better.


It’s important to notice that client and server are running on the same machine here (a
Windows PC). The server and client agree on the port number, but they use the machine
names "" and localhost, respectively, to refer to the computer on which they are run-
ning. In fact, there is no Internet connection to speak of. This is just IPC, of the sort
we saw in Chapter 5: sockets also work well as cross-program communications tools
on a single machine.


794 | Chapter 12: Network Scripting

Free download pdf