Regarding the Python gevent TCP server problem, about TCPServer, each client connects to TCPServer when Gevent automatically assigns a greenlet execution, but how to listen to each SOKCET client's message receive , see the code is used in the Greenlet method loop receive, there is no callback it?
Reply content:
One of the great advantages of gevent compared to other frameworks (such as tornado,twisted) is that asynchronous applications are written in a synchronous way (naturally without a callback function), because synchronization is closer to developers ' programming thinking.
Gevent can be described in a sentence to Pythoner: Use the multi-io multiplexing of the file descriptor to listen to the event, thus pry the "transparent" switch of the co-path. It's easy to say, but it's more complicated to explain:
- The underlying (or main) process naturally has a multi-channel multiplexing Loop (Epoll,unix is kqueue on Linux and the following unified Epoll instead of description)
- When a socket link is processed, a greenlet is created to handle it.
- When the socket is blocked, such as waiting for data to be returned or sent, Gevent does a critical two-step:
- The FD for this socket adds a readable or writable event callback to the Epoll, and this callback function is gevent.getcurrent (). switch
- Switch to the main coprocessor by Get_hub (). Switch back to the main process to do something else. However, when the socket is readable or writable, Epoll will naturally invoke the callback function added above, thus switching back to the processing of the socket and executing from the last hanging point.
The reason for transparency is because the python socket has patches on it. The so-called patch, is the implementation of a socket module to replace the Python standard socket module.
Def patch_socket ():
From gevent import socket
_socket = __import__ (' socket ')
_socket.socket = Socket.socket
...
Gevent implementation of the socket module, compared to the Python standard socket module, the following changes were made:
- Set all sockets to non-blocking.
- Modify key functions, such as SEND,RECV, when blocking (catch to Exception ewouldblock), add a callback function to the FD of the socket and jump back to the main process.
To sum up, gevent is not without an event listener callback, but by making patches for Python sockets to make it transparent, eventually enabling programmers to develop with synchronized thinking.
PS, to Python socket patch, is good, but there is a small drawback, is:
The socket in the Python C extension module is not controlled and dispatched by Gevent, so the network library used in the gevent uses the Pure Python library as much as possible .。 Here this loop is the loop that drives the entire session of a client. The entire echo is executed in a greenlet when a client connects to the Streamserver listening port and is treated as a callback.