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

(yzsuai) #1

a connection is accepted, to simulate a long-running task (this is from file echo-server-
sleep.py in the examples package if you wish to experiment):


while True: # listen until process killed
connection, address = sockobj.accept() # wait for next client connect
while True:
data = connection.recv(1024) # read next line on client socket
time.sleep(3) # take time to process request
...

If you then run this server and the testecho clients script, you’ll notice that not all 8
clients wind up receiving a connection, because the server is too busy to empty its
pending-connections queue in time. Only 6 clients are served when I run this on Win-
dows—one accepted initially, and 5 in the pending-requests listen queue. The other
two clients are denied connections and fail.


The following shows the server and client messages produced when the server is stalled
this way, including the error messages that the two denied clients receive. To see the
clients’ messages on Windows, you can change testecho to use the StartArgs launcher
with a /B switch at the front of the command line to route messages to the persistent
console window (see file testecho-messages.py in the examples package):


C:\...\PP4E\dev\Examples\PP4E\Internet\Sockets> echo-server-sleep.py
Server connected by ('127.0.0.1', 59625)
Server connected by ('127.0.0.1', 59626)
Server connected by ('127.0.0.1', 59627)
Server connected by ('127.0.0.1', 59628)
Server connected by ('127.0.0.1', 59629)
Server connected by ('127.0.0.1', 59630)

C:\...\PP4E\dev\Examples\PP4E\Internet\Sockets> testecho-messages.py
/B echo-client.py
/B echo-client.py
/B echo-client.py
/B echo-client.py
/B echo-client.py
/B echo-client.py
/B echo-client.py
/B echo-client.py
Client received: b'Echo=>Hello network world'

Traceback (most recent call last):
File "C:\...\PP4E\Internet\Sockets\echo-client.py", line 24, in <module>
sockobj.connect((serverHost, serverPort)) # connect to server machine...
socket.error: [Errno 10061] No connection could be made because the target
machine actively refused it

Traceback (most recent call last):
File "C:\...\PP4E\Internet\Sockets\echo-client.py", line 24, in <module>
sockobj.connect((serverHost, serverPort)) # connect to server machine...
socket.error: [Errno 10061] No connection could be made because the target
machine actively refused it

800 | Chapter 12: Network Scripting

Free download pdf