程式扎記: [Python 文章收集] select – Wait for I/O Efficiently

標籤

2016年11月29日 星期二

[Python 文章收集] select – Wait for I/O Efficiently

Source From Here
Preface
The select module provides access to platform-specific I/O monitoring functions. The most portable interface is the POSIX function select(), which is available on Unix and Windows. The module also includes poll(), a Unix-only API, and several options that only work with specific variants of Unix.

select()
Python’s select() function is a direct interface to the underlying operating system implementation. It monitors sockets, open files, and pipes (anything with a fileno() method that returns a valid file descriptoruntil they become readable or writable, or a communication error occursselect() makes it easier to monitor multiple connections at the same time, and is more efficient than writing a polling loop in Python using socket timeouts, because the monitoring happens in the operating system network layer, instead of the interpreter.
Note. Using Python’s file objects with select() works for Unix, but is not supported under Windows.

The echo server example from the socket section can be extended to watch for more than one connection at a time by using select():
  1. import select  
  2. import socket  
  3. import sys  
  4. import Queue  
  5.   
  6. # Create a TCP/IP socket  
  7. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  8. server.setblocking(0)  
  9.   
  10. # Bind the socket to the port  
  11. server_address = ('localhost'10000)  
  12. print >>sys.stderr, 'starting up on %s port %s' % server_address  
  13. server.bind(server_address)  
  14.   
  15. # Listen for incoming connections  
  16. server.listen(5)  
The arguments to select() are three lists containing communication channels to monitor. The first is a list of the objects to be checked for incoming data to be read, the second contains objects that will receive outgoing data when there is room in their buffer, and the third those that may have an error (usually a combination of the input and output channel objects). The next step in the server is to set up the lists containing input sources and output destinations to be passed to select().
  1. # Sockets from which we expect to read  
  2. inputs = [ server ]  
  3.   
  4. # Sockets to which we expect to write  
  5. outputs = [ ]  
Connections are added to and removed from these lists by the server main loop. Since this version of the server is going to wait for a socket to become writable before sending any data (instead of immediately sending the reply), each output connection needs a queue to act as a buffer for the data to be sent through it.
  1. # Outgoing message queues (socket:Queue)  
  2. message_queues = {}  
The main portion of the server program loops, calling select() to block and wait for network activity.
  1. while inputs:  
  2.     # Wait for at least one of the sockets to be ready for processing  
  3.     print >>sys.stderr, '\nwaiting for the next event'  
  4.     readable, writable, exceptional = select.select(inputs, outputs, inputs)  
select() returns three new lists, containing subsets of the contents of the lists passed in. All of the sockets in the readable list have incoming data buffered and available to be read. All of the sockets in the writable list have free space in their buffer and can be written to. The sockets returned in exceptional have had an error (the actual definition of “exceptional condition” depends on the platform).

The “readable” sockets represent three possible cases. If the socket is the main “server” socket, the one being used to listen for connections, then the “readable” condition means it is ready to accept another incoming connection. In addition to adding the new connection to the list of inputs to monitor, this section sets the client socket to not block.
  1. # Handle inputs  
  2. for s in readable:  
  3.   
  4.     if s is server:  
  5.         # A "readable" server socket is ready to accept a connection  
  6.         connection, client_address = s.accept()  
  7.         print >>sys.stderr, 'new connection from', client_address  
  8.         connection.setblocking(0)  
  9.         inputs.append(connection)  
  10.   
  11.         # Give the connection a queue for data we want to send  
  12.         message_queues[connection] = Queue.Queue()  
The next case is an established connection with a client that has sent data. The data is read with recv(), then placed on the queue so it can be sent through the socket and back to the client.
  1. else:  
  2.     data = s.recv(1024)  
  3.     if data:  
  4.         # A readable client socket has data  
  5.         print >>sys.stderr, 'received "%s" from %s' % (data, s.getpeername())  
  6.         message_queues[s].put(data)  
  7.         # Add output channel for response  
  8.         if s not in outputs:  
  9.             outputs.append(s)  
A readable socket without data available is from a client that has disconnected, and the stream is ready to be closed.
  1. else:  
  2.     # Interpret empty result as closed connection  
  3.     print >>sys.stderr, 'closing', client_address, 'after reading no data'  
  4.     # Stop listening for input on the connection  
  5.     if s in outputs:  
  6.         outputs.remove(s)  
  7.     inputs.remove(s)  
  8.     s.close()  
  9.   
  10.     # Remove message queue  
  11.     del message_queues[s]  
There are fewer cases for the writable connections. If there is data in the queue for a connection, the next message is sent. Otherwise, the connection is removed from the list of output connections so that the next time through the loop select() does not indicate that the socket is ready to send data.
  1. # Handle outputs  
  2. for s in writable:  
  3.     try:  
  4.         next_msg = message_queues[s].get_nowait()  
  5.     except Queue.Empty:  
  6.         # No messages waiting so stop checking for writability.  
  7.         print >>sys.stderr, 'output queue for', s.getpeername(), 'is empty'  
  8.         outputs.remove(s)  
  9.     else:  
  10.         print >>sys.stderr, 'sending "%s" to %s' % (next_msg, s.getpeername())  
  11.         s.send(next_msg)  
Finally, if there is an error with a socket, it is closed.
  1. # Handle "exceptional conditions"  
  2. for s in exceptional:  
  3.     print >>sys.stderr, 'handling exceptional condition for', s.getpeername()  
  4.     # Stop listening for input on the connection  
  5.     inputs.remove(s)  
  6.     if s in outputs:  
  7.         outputs.remove(s)  
  8.     s.close()  
  9.   
  10.     # Remove message queue  
  11.     del message_queues[s]  
The example client program uses two sockets to demonstrate how the server with select() manages multiple connections at the same time. The client starts by connecting each TCP/IP socket to the server.
  1. import socket  
  2. import sys  
  3.   
  4. messages = [ 'This is the message. ',  
  5.              'It will be sent ',  
  6.              'in parts.',  
  7.              ]  
  8. server_address = ('localhost'10000)  
  9.   
  10. # Create a TCP/IP socket  
  11. socks = [ socket.socket(socket.AF_INET, socket.SOCK_STREAM),  
  12.           socket.socket(socket.AF_INET, socket.SOCK_STREAM),  
  13.           ]  
  14.   
  15. # Connect the socket to the port where the server is listening  
  16. print >>sys.stderr, 'connecting to %s port %s' % server_address  
  17. for s in socks:  
  18.     s.connect(server_address)  
Then it sends one pieces of the message at a time via each socket, and reads all responses available after writing new data.
  1. for message in messages:  
  2.   
  3.     # Send messages on both sockets  
  4.     for s in socks:  
  5.         print >>sys.stderr, '%s: sending "%s"' % (s.getsockname(), message)  
  6.         s.send(message)  
  7.   
  8.     # Read responses on both sockets  
  9.     for s in socks:  
  10.         data = s.recv(1024)  
  11.         print >>sys.stderr, '%s: received "%s"' % (s.getsockname(), data)  
  12.         if not data:  
  13.             print >>sys.stderr, 'closing socket', s.getsockname()  
  14.             s.close()  
Run the server in one window and the client in another. The output will look like this, with different port numbers.
$ python ./select_echo_server.py
starting up on localhost port 10000

waiting for the next event
new connection from ('127.0.0.1', 55821)

waiting for the next event
new connection from ('127.0.0.1', 55822)
received "This is the message. " from ('127.0.0.1', 55821)

waiting for the next event
sending "This is the message. " to ('127.0.0.1', 55821)
...

The client output shows the data being sent and received using both sockets.
$ python ./select_echo_multiclient.py
connecting to localhost port 10000
('127.0.0.1', 55821): sending "This is the message. "
('127.0.0.1', 55822): sending "This is the message. "
('127.0.0.1', 55821): received "This is the message. "
('127.0.0.1', 55822): received "This is the message. "
('127.0.0.1', 55821): sending "It will be sent "
('127.0.0.1', 55822): sending "It will be sent "
('127.0.0.1', 55821): received "It will be sent "
...


Timeouts
select() also takes an optional fourth parameter which is the number of seconds to wait before breaking off monitoring if no channels have become active. Using a timeout value lets a main program call select() as part of a larger processing loop, taking other actions in between checking for network input.

When the timeout expires, select() returns three empty lists. Updating the server example to use a timeout requires adding the extra argument to the select() call and handling the empty lists after select() returns.
  1. # Wait for at least one of the sockets to be ready for processing  
  2. print >>sys.stderr, '\nwaiting for the next event'  
  3. timeout = 1  
  4. readable, writable, exceptional = select.select(inputs, outputs, inputs, timeout)  
  5.   
  6. if not (readable or writable or exceptional):  
  7.     print >>sys.stderr, '  timed out, do some other work here'  
  8.     continue  
This “slow” version of the client program pauses after sending each message, to simulate latency or other delay in transmission.
  1. import socket  
  2. import sys  
  3. import time  
  4.   
  5. # Create a TCP/IP socket  
  6. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  7.   
  8. # Connect the socket to the port where the server is listening  
  9. server_address = ('localhost'10000)  
  10. print >>sys.stderr, 'connecting to %s port %s' % server_address  
  11. sock.connect(server_address)  
  12.   
  13. time.sleep(1)  
  14.   
  15. messages = [ 'Part one of the message.',  
  16.              'Part two of the message.',  
  17.              ]  
  18. amount_expected = len(''.join(messages))  
  19.   
  20. try:  
  21.   
  22.     # Send data  
  23.     for message in messages:  
  24.         print >>sys.stderr, 'sending "%s"' % message  
  25.         sock.sendall(message)  
  26.         time.sleep(1.5)  
  27.   
  28.     # Look for the response  
  29.     amount_received = 0  
  30.       
  31.     while amount_received < amount_expected:  
  32.         data = sock.recv(16)  
  33.         amount_received += len(data)  
  34.         print >>sys.stderr, 'received "%s"' % data  
  35.   
  36. finally:  
  37.     print >>sys.stderr, 'closing socket'  
  38.     sock.close()  
Running the new server with the slow client produces:
$ python ./select_echo_server_timeout.py
starting up on localhost port 10000

waiting for the next event
timed out
...

And the client output is:
$ python ./select_echo_slow_client.py
connecting to localhost port 10000
sending "Part one of the message."
sending "Part two of the message."
received "Part one of the "
received "message.Part two"
...

poll()
The poll() function provides similar features to select(), but the underlying implementation is more efficient. The trade-off is that poll() is not supported under Windows, so programs using poll() are less portable. An echo server built on poll() starts with the same socket configuration code used in the other examples.
  1. import select  
  2. import socket  
  3. import sys  
  4. import Queue  
  5.   
  6. # Create a TCP/IP socket  
  7. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  8. server.setblocking(0)  
  9.   
  10. # Bind the socket to the port  
  11. server_address = ('localhost'10000)  
  12. print >>sys.stderr, 'starting up on %s port %s' % server_address  
  13. server.bind(server_address)  
  14.   
  15. # Listen for incoming connections  
  16. server.listen(5)  
  17.   
  18. # Keep up with the queues of outgoing messages  
  19. message_queues = {}  
The timeout value passed to poll() is represented in milliseconds, instead of seconds, so in order to pause for a full second the timeout must be set to 1000.
  1. # Do not block forever (milliseconds)  
  2. TIMEOUT = 1000  
Python implements poll() with a class that manages the registered data channels being monitored. Channels are added by calling register() with flags indicating which events are interesting for that channel. The full set of flags is:


The echo server will be setting up some sockets just for reading, and others to be read from or written to. The appropriate combinations of flags are saved to the local variables READ_ONLY and READ_WRITE.
# Commonly used flag setes
  1. READ_ONLY = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR  
  2. READ_WRITE = READ_ONLY | select.POLLOUT  
The server socket is registered so that any incoming connections or data triggers an event.
  1. # Set up the poller  
  2. poller = select.poll()  
  3. poller.register(server, READ_ONLY)  
Since poll() returns a list of tuples containing the file descriptor for the socket and the event flag, a mapping from file descriptor numbers to objects is needed to retrieve the socket to read or write from it.
  1. # Map file descriptors to socket objects  
  2. fd_to_socket = { server.fileno(): server,  
  3.                }  
The server’s loop calls poll(), then processes the “events” returned by looking up the socket and taking action based on the flag in the event.
  1. while True:  
  2.   
  3.     # Wait for at least one of the sockets to be ready for processing  
  4.     print >>sys.stderr, '\nwaiting for the next event'  
  5.     events = poller.poll(TIMEOUT)  
  6.   
  7.     for fd, flag in events:  
  8.   
  9.         # Retrieve the actual socket from its file descriptor  
  10.         s = fd_to_socket[fd]  
As with select(), when the main server socket is “readable,” that really means there is a pending connection from a client. The new connection is registered with the READ_ONLY flags to watch for new data to come through it.
  1. # Handle inputs  
  2. if flag & (select.POLLIN | select.POLLPRI):  
  3.   
  4.     if s is server:  
  5.         # A "readable" server socket is ready to accept a connection  
  6.         connection, client_address = s.accept()  
  7.         print >>sys.stderr, 'new connection from', client_address  
  8.         connection.setblocking(0)  
  9.         fd_to_socket[ connection.fileno() ] = connection  
  10.         poller.register(connection, READ_ONLY)  
  11.   
  12.         # Give the connection a queue for data we want to send  
  13.         message_queues[connection] = Queue.Queue()  
  14.     else:  
  15.         data = s.recv(1024)  
Sockets other than the server are existing clients, and recv() is used to access the data waiting to be read. If recv() returns any data, it is placed into the outgoing queue for the socket and the flags for that socket are changed using modify() so poll() will watch for the socket to be ready to receive data.
  1. if data:  
  2.     # A readable client socket has data  
  3.     print >>sys.stderr, 'received "%s" from %s' % (data, s.getpeername())  
  4.     message_queues[s].put(data)  
  5.     # Add output channel for response  
  6.     poller.modify(s, READ_WRITE)  
An empty string returned by recv() means the client disconnected, so unregister() is used to tell the poll object to ignore the socket.
  1. else:  
  2.     # Interpret empty result as closed connection  
  3.     print >>sys.stderr, 'closing', client_address, 'after reading no data'  
  4.     # Stop listening for input on the connection  
  5.     poller.unregister(s)  
  6.     s.close()  
  7.   
  8.     # Remove message queue  
  9.     del message_queues[s]  
The POLLHUP flag indicates a client that “hung up” the connection without closing it cleanly. The server stops polling clients that disappear.
  1. elif flag & select.POLLHUP:  
  2.     # Client hung up  
  3.     print >>sys.stderr, 'closing', client_address, 'after receiving HUP'  
  4.     # Stop listening for input on the connection  
  5.     poller.unregister(s)  
  6.     s.close()  
The handling for writable sockets looks like the version used in the example for select(), except that modify() is used to change the flags for the socket in the poller, instead of removing it from the output list.
  1. elif flag & select.POLLOUT:  
  2.     # Socket is ready to send data, if there is any to send.  
  3.     try:  
  4.         next_msg = message_queues[s].get_nowait()  
  5.     except Queue.Empty:  
  6.         # No messages waiting so stop checking for writability.  
  7.         print >>sys.stderr, 'output queue for', s.getpeername(), 'is empty'  
  8.         poller.modify(s, READ_ONLY)  
  9.     else:  
  10.         print >>sys.stderr, 'sending "%s" to %s' % (next_msg, s.getpeername())  
  11.         s.send(next_msg)  
And finally, any events with POLLERR cause the server to close the socket.
  1. elif flag & select.POLLERR:  
  2.     print >>sys.stderr, 'handling exceptional condition for', s.getpeername()  
  3.     # Stop listening for input on the connection  
  4.     poller.unregister(s)  
  5.     s.close()  
  6.   
  7.     # Remove message queue  
  8.     del message_queues[s]  
When the poll-based server is run together with select_echo_multiclient.py (the client program that uses multiple sockets), the output is:
$ python ./select_poll_echo_server.py
starting up on localhost port 10000

waiting for the next event

waiting for the next event

waiting for the next event
new connection from ('127.0.0.1', 58447)

waiting for the next event
new connection from ('127.0.0.1', 58448)
received "This is the message. " from ('127.0.0.1', 58447)

waiting for the next event
sending "This is the message. " to ('127.0.0.1', 58447)
received "This is the message. " from ('127.0.0.1', 58448)

waiting for the next event
output queue for ('127.0.0.1', 58447) is empty
sending "This is the message. " to ('127.0.0.1', 58448)
...

This message was edited 45 times. Last update was at 29/11/2016 19:42:29

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!