Today, when worshipping Shadsocks code, the great God's code is so beautifully
The situation that occurs is basically as follows:
1 Initialize a tcphandler, of course he didn't call it that.
2 Initializes a eventloop.
3 Put this tcphandler into the eventloop.
After 4, add the code in the EventLoop under Tcphandler.
Can see
Self._eventloop.add (Self._server_socket, eventloop. poll_in | EventLoop. Poll_err, self) finally passes in to self, and the Tcphandler reference is passed.
defAdd_to_loop (self, loop):ifSelf._eventloop:RaiseException ('already add to loop') ifself._closed:RaiseException ('already closed') Self._eventloop=Loop Self._eventloop.add (Self._server_socket, EventLoop. Poll_in|EventLoop. Poll_err, self) self._eventloop.add_periodic (self.handle_periodic)
5 EventLoop is the driver base of the whole program, he comes to handle the problem of socket polling. But he doesn't deal with data problems with sockets. So there's this variable inside:
Self._fdmap = {} # (F, Handler)
F is Fileno (). We know that Fileno () is going to return stream status. Usually refers to file descriptor, here is stream descriptor. Of course file is also stream processing.
What does that mean, a socket is stored, corresponding to a handler.
6: How to call this callback function?
for inch Events: = Self._fdmap.get (fd, none) if is not None: = handler[1] Try : handler.handle_event (sock, FD, event) except (OSError, IOError) as E: Shell.print_exception (e)
It is clear that when polling the socket, it is still handled with the handler that generated the socket.
This is a nice design.
The callback function says that the simple point is the back function.
Eg:callback_function ()--->invoke callback_function.some_function (self)---> some_function ()-->invoke Callbackfunction () [[[The call will need to use the passed self]]]
Understand this, the basic understanding of the whole Shadowsocks program.
Python callback function