由python端口转发脚本看asyncore模块

    asyncore模块是封装过的处理socket事件的模块,在文档中搜索可以看到这样的说明:

Basic infrastructure for asynchronous socket service clients and servers.
There are only two ways to have a program on a single processor do “more
than one thing at a time”. Multi-threaded programming is the simplest and
most popular way to do it, but there is another very different technique,
that lets you have nearly all the advantages of multi-threading, without
actually using multiple threads. it’s really only practical if your program
is largely I/O bound. If your program is CPU bound, then pre-emptive
scheduled threads are probably what you really need. Network servers are
rarely CPU-bound, however.
If your operating system supports the select() system call in its I/O
library (and nearly all do), then you can use it to juggle multiple
communication channels at once; doing other work while your I/O is taking
place in the “background.” Although this strategy can seem strange and
complex, especially at first, it is in many ways easier to understand and
control than multi-threaded programming. The module documented here solves
many of the difficult problems for you, making the task of building
sophisticated high-performance network servers and clients a snap.

    大概意思是,如果你的程序想在同一时间做一件一上的事情,多线程是最快也最普遍的方式,但还有一个方式,在I/O流量很大的时候特别实用。如果你的操作系统支持select函数,你就可以让I/O在后台读写。这个模块听起来很复杂,但实际上有很多方式可以理解它,这个文档帮你解决了这些问题。

    我感觉这个模块应该是一个以事件驱动的异步I/O,跟C++的事件选择模型类似。每当发生了读、写事件后,会交由我们重写的事件函数进行处理。

    我这里有一个使用asyncore模块编写端口转发脚本,从这个脚本可以大概了解asyncore的基本使用。

    在文章中,所说的客户端就是我们的电脑,服务端是转发到的地址。也就是客户端发送到这个脚本的信息,这个脚本转发到服务端上。

    首先,定义一个forwarder类:

class forwarder(asyncore.dispatcher):
    def __init__(self, ip, port, remoteip,remoteport,backlog=5):
        asyncore.dispatcher.__init__(self)
        self.remoteip=remoteip
        self.remoteport=remoteport
        self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((ip,port))
        self.listen(backlog)

    def handle_accept(self):
        conn, addr = self.accept()
        # print '--- Connect --- '
        sender(receiver(conn),self.remoteip,self.remoteport)

    这个类继承自asyncore模块的dispatcher类(它就是我们的主要的类,其中包括了一些之后要重载的函数),构造函数获得5个参数,第1、2个参数是脚本监听的本地IP和端口,第3、4个参数是服务端的IP和端口。第5个参数是listen函数的参数,等待队列最大长度。

    如何使用这个类,只需要如下新建一个对象,把相应IP和端口传入,再进入loop即可:

    forwarder(options.local_ip,options.local_port,options.remote_ip,options.remote_port)
    asyncore.loop()

    进入loop后相当于开启了一个守护线程,在后台一直运行着,等待socket事件的发生。

    因为我们这个脚本是端口转发工具,所以实际上运行的过程是:客户端连接这个脚本的端口,让后发送给这个端口的数据脚本自动转发到服务端地址和端口。所以,首先接收到的应该是连接消息(accept事件)。

    那么,当accept事件发生后,就进入了handle_accept函数中。所以我们看到,handle_accept函数实际上就是调用了accept函数接收了客户端连接对象和地址。获得了之后又新建了一个sender类对象,这个对象定义如下:

class sender(asyncore.dispatcher):
    def __init__(self, receiver, remoteaddr,remoteport):
        asyncore.dispatcher.__init__(self)
        self.receiver=receiver
        receiver.sender=self
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((remoteaddr, remoteport))

    def handle_connect(self):
        pass

    def handle_read(self):
        read = self.recv(4096)
        # print '<-- %04i'%len(read)
        self.receiver.to_remote_buffer += read

    def writable(self):
        return (len(self.receiver.from_remote_buffer) > 0)

    def handle_write(self):
        sent = self.send(self.receiver.from_remote_buffer)
        # print '--> %04i'%sent
        self.receiver.from_remote_buffer = self.receiver.from_remote_buffer[sent:]

    def handle_close(self):
        self.close()
        self.receiver.close()

    这个类也是继承自asyncore.dispatcher,它的构造函数接收3个参数,分别是recv对象(这个之后说到),远端地址,对应端口。

    函数中又新建了一个socket,这个socket就是和服务端端口通信的socket,然后调用connect连接这个端口。

    之后其实也是进入了一个等待消息的过程,因为我们发送了一个connect,所以下一次接收到的消息应该是connect,而handle_connect是一个pass掉的函数。没有执行任何内容。

    在连接完成后,我们就相当于建立好了一个端口转发的通道。当客户端向这个脚本监听的端口发送数据包时,它就会自动转发到服务端端口上。服务端端口返回的数据包,会自动转发到客户端上。

    回到构造函数的第1个参数,我们在forwarder类函数中可以看到,传入的是一个receiver(conn)对象,receiver也是一个类,我们来看看这个类的定义:

class receiver(asyncore.dispatcher):
    def __init__(self,conn):
        asyncore.dispatcher.__init__(self,conn)
        self.from_remote_buffer=''
        self.to_remote_buffer=''
        self.sender=None

    def handle_connect(self):
        pass

    def handle_read(self):
        read = self.recv(4096)
        # print '%04i -->'%len(read)
        self.from_remote_buffer += read

    def writable(self):
        return (len(self.to_remote_buffer) > 0)

    def handle_write(self):
        sent = self.send(self.to_remote_buffer)
        # print '%04i <--'%sent
        self.to_remote_buffer = self.to_remote_buffer[sent:]

    def handle_close(self):
        self.close()
        if self.sender:
            self.sender.close()

    它也是继承了asyncore.dispatcher,构造函数只接收一个参数,就是connect的返回值,一个连接对象。

    实际上这个对象它就是监听、处理与客户端的通信,而之前说的sender对象是监听、处理与服务端的通信。

    大家可以查看处理这些socket消息的函数,来深入理解整个转发的过程,我这里就不多说了。

    文档在http://docs.python.org/2/library/asyncore.html 大家可以参考。

© 版权声明
THE END
喜欢就支持一下吧
点赞0
分享
评论 抢沙发

请登录后发表评论