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

(yzsuai) #1

modules do the same for other standard ports (e.g., NNTP, Telnet, and so on). We’ll
meet some of these client-side protocol modules in the next chapter.§


Binding reserved port servers


Speaking of reserved ports, it’s all right to open client-side connections on reserved
ports as in the prior section, but you can’t install your own server-side scripts for these
ports unless you have special permission. On the server I use to host learning-
python.com, for instance, the web server port 80 is off limits (presumably, unless I shell
out for a virtual or dedicated hosting account):


[...]$ python
>>> from socket import *
>>> sock = socket(AF_INET, SOCK_STREAM) # try to bind web port on general server
>>> sock.bind(('', 80)) # learning-python.com is a shared machine
Traceback (most recent call last):
File "<stdin>", line 1, in
File "<string>", line 1, in bind
socket.error: (13, 'Permission denied')

Even if run by a user with the required permission, you’ll get the different exception
we saw earlier if the port is already being used by a real web server. On computers being
used as general servers, these ports really are reserved. This is one reason we’ll run a
web server of our own locally for testing when we start writing server-side scripts later
in this book—the above code works on a Windows PC, which allows us to experiment
with websites locally, on a self-contained machine:


C:\...\PP4E\Internet\Sockets> python
>>> from socket import *
>>> sock = socket(AF_INET, SOCK_STREAM) # can bind port 80 on Windows
>>> sock.bind(('', 80)) # allows running server on localhost
>>>

We’ll learn more about installing web servers later in Chapter 15. For the purposes of
this chapter, we need to get realistic about how our socket servers handle their clients.


Handling Multiple Clients


The echo client and server programs shown previously serve to illustrate socket funda-
mentals. But the server model used suffers from a fairly major flaw. As described earlier,
if multiple clients try to connect to the server, and it takes a long time to process a given
client’s request, the server will fail. More accurately, if the cost of handling a given


§You might be interested to know that the last part of this example, talking to port 80, is exactly what your
web browser does as you surf the Web: followed links direct it to download web pages over this port. In fact,
this lowly port is the primary basis of the Web. In Chapter 15, we will meet an entire application environment
based upon sending formatted data over port 80—CGI server-side scripting. At the bottom, though, the Web
is just bytes over sockets, with a user interface. The wizard behind the curtain is not as impressive as he may
seem!


802 | Chapter 12: Network Scripting

Free download pdf