实现一个程序, 原意是结合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 这么写是什么意思, 为什么要这么写
新手, 也许问题问的并不适合,但真心求教
学习是最好的投资!