Python asyncore接收类对象进行转发问题,pythonasyncore,实现一个程序, 原意是结
Python asyncore接收类对象进行转发问题,pythonasyncore,实现一个程序, 原意是结
实现一个程序, 原意是结合argparse接收命令行参数, 然后通过asyncore进行转发, 从而实现
我在命令行下执行程序监听一个端口,当在浏览器里输入localhost:port的时候,自动转发到远程remoteaddr, 然后再接收转发的conn返回给client,代码是这样的。
import argparse import asyncoreimport socketLOCAL_SERVER_HOST = 'localhost'REMOTE_SERVER_HOST = 'www.domain.com'BUFSIZE = 4096class 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 这么写是什么意思, 为什么要这么写
新手, 也许问题问的并不适合,但真心求教
编橙之家文章,
相关内容
- BeautifulSoup实体引用应该怎样做,beautifulsoup实体,templa
- supervisord event如何配置添加,supervisordevent,如何配置su
- 要在项目中扩展下载类库应该用什么方法,项目类库
- Python 正则中文网页字符串提取问题,python中文网页,&
- 请问这个Python程序运行原理是什么,Python程序运行原理
- 需要为遵守PEP8修改自己python代码吗,遵守pep8python代码
- Python利用二分法计算平方根哪里出问题了,python二分法
- 新手请教关于Flask-sqlalchemy、Flask-WTF结合查询的问题,
- Python实现批量生成字符串最佳思路是什么,python思路
- Python2.7遍历包含一个dict的tuple变量应该怎么写,python
评论关闭