玩蛇网提供最新Python编程技术信息以及Python资源下载!
您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容

Python asyncore接收类对象进行转发问题

实现一个程序, 原意是结合argparse接收命令行参数, 然后通过asyncore进行转发, 从而实现
我在命令行下执行程序监听一个端口,当在浏览器里输入localhost:port的时候,自动转发到远程remoteaddr, 然后再接收转发的conn返回给client,代码是这样的。

import argparse 
import asyncore
import socket
LOCAL_SERVER_HOST = 'localhost'
REMOTE_SERVER_HOST = 'www.domain.com'
BUFSIZE = 4096
class PortForward(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('Connected',addr)
        Sender(Receiver(conn),self.remoteip,self.remoteport) #这里,是在Sender类里传入一个Receiver类对象方法,与下面的self.receiver = receiver #传入相对应,因为需要使用Sender发送,所以要把传入的receiver绑定成当前自己sender,或者说绑定到sender上。

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)
        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)
        self.to_remote_buffer = self.to_remote_buffer[sent:]
    def handle_close(self):
        self.close()
        if self.sender:
            self.sender.close()
class Sender(asyncore.dispatcher):
    def __init__(self,receiver,remoteaddr,remoteport):
        asyncore.dispatcher.__init__(self)
        self.receiver = receiver #传入一个receiver对象
        receiver.sender = self #把receiver对象绑定成自己
        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)
        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)
        self.receiver.from_remote_buffer = self.receiver.from_remote_buffer[sent:]
    def handle_close(self):
        self.close()
        self.receiver.close()

Sender负责把接收到的发给服务端, Receiver负责把发送返回的conn反馈给client,比较疑惑的就是
self.receiver.from_remote_buffer self.receiver.to_remote_buffer 这么写是什么意思, 为什么要这么写

新手, 也许问题问的并不适合,但真心求教

玩蛇网文章,转载请注明出处和文章网址:http://www.iplaypy.com/wenda/wd18572.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年06月02日 - 17时07分38秒 发布自玩蛇网

我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules