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

(yzsuai) #1

running; in our scripts, server and client agree to use port number 50007 for their
conversation, outside the standard protocol range. Here are the client’s socket calls:


sockobj = socket(AF_INET, SOCK_STREAM)
Creates a Python socket object in the client program, just like the server.


sockobj.connect((serverHost, serverPort))
Opens a connection to the machine and port on which the server program is lis-
tening for client connections. This is where the client specifies the string name of
the service to be contacted. In the client, we can either specify the name of the
remote machine as a domain name (e.g., starship.python.net) or numeric IP ad-
dress. We can also give the server name as localhost (or the equivalent IP address
127.0.0.1) to specify that the server program is running on the same machine as
the client; that comes in handy for debugging servers without having to connect
to the Net. And again, the client’s port number must match the server’s exactly.
Note the nested parentheses again—just as in server bind calls, we really pass the
server’s host/port address to connect in a tuple object.


Once the client establishes a connection to the server, it falls into a loop, sending a
message one line at a time and printing whatever the server sends back after each line
is sent:


sockobj.send(line)
Transfers the next byte-string message line to the server over the socket. Notice
that the default list of lines contains bytes strings (b'...'). Just as on the server,
data passed through the socket must be a byte string, though it can be the result
of a manual str.encode encoding call or an object conversion with pickle or
struct if desired. When lines to be sent are given as command-line arguments
instead, they must be converted from str to bytes; the client arranges this by en-
coding in a generator expression (a call map(str.encode, sys.argv[2:]) would have
the same effect).


data = sockobj.recv(1024)
Reads the next reply line sent by the server program. Technically, this reads up to
1,024 bytes of the next reply message and returns it as a byte string.


sockobj.close()
Closes the connection with the server, sending it the end-of-file signal.


And that’s it. The server exchanges one or more lines of text with each client that
connects. The operating system takes care of locating remote machines, routing bytes
sent between programs and possibly across the Internet, and (with TCP) making sure
that our messages arrive intact. That involves a lot of processing, too—our strings may
ultimately travel around the world, crossing phone wires, satellite links, and more along
the way. But we can be happily ignorant of what goes on beneath the socket call layer
when programming in Python.


Socket Programming | 793
Free download pdf