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

(yzsuai) #1
Client received: b'Echo=>Hello network world'
Client received: b'Echo=>Hello network world'
Client received: b'Echo=>Hello network world'
Client received: b'Echo=>Hello network world'
Client received: b'Echo=>Hello network world'

As you can see, with such a sleepy server, 8 clients are spawned, but only 6 receive
service, and 2 fail with exceptions. Unless clients require very little of the server’s at-
tention, to handle multiple requests overlapping in time we need to somehow service
clients in parallel. We’ll see how servers can handle multiple clients more robustly in
a moment; first, though, let’s experiment with some special ports.


Talking to Reserved Ports


It’s also important to know that this client and server engage in a proprietary sort of
discussion, and so use the port number 50007 outside the range reserved for standard
protocols (0 to 1023). There’s nothing preventing a client from opening a socket on
one of these special ports, however. For instance, the following client-side code con-
nects to programs listening on the standard email, FTP, and HTTP web server ports
on three different server machines:


C:\...\PP4E\Internet\Sockets> python
>>> from socket import *
>>> sock = socket(AF_INET, SOCK_STREAM)
>>> sock.connect(('pop.secureserver.net', 110)) # talk to POP email server
>>> print(sock.recv(70))
b'+OK <[email protected]>\r\n'
>>> sock.close()

>>> sock = socket(AF_INET, SOCK_STREAM)
>>> sock.connect(('learning-python.com', 21)) # talk to FTP server
>>> print(sock.recv(70))
b'220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------\r\n220-You'
>>> sock.close()

>>> sock = socket(AF_INET, SOCK_STREAM)
>>> sock.connect(('www.python.net', 80)) # talk to Python's HTTP server

>>> sock.send(b'GET /\r\n') # fetch root page reply
7
>>> sock.recv(70)
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\r\n "http://'
>>> sock.recv(70)
b'www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\r\n<html xmlns="http://www.'

If we know how to interpret the output returned by these ports’ servers, we could use
raw sockets like this to fetch email, transfer files, and grab web pages and invoke server-
side scripts. Fortunately, though, we don’t have to worry about all the underlying de-
tails—Python’s poplib, ftplib, and http.client and urllib.request modules provide
higher-level interfaces for talking to servers on these ports. Other Python protocol


Socket Programming | 801
Free download pdf