用vb.net写过一个, 效果不太好, 现在用python重写了一下。
#!/usr/bin/python import sys, socket, threading, subprocess fromport=80 toport=80 server='twd2.me' max_conn=100 class TransConn(threading.Thread): def __init__(self, fr): threading.Thread.__init__(self) self.fr=fr self.to=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.running=True def tran1(self): try: while self.running: print('tran1 - reading') r=self.fr.recv(8192) print('tran1 - ' + str(len(r))) if len(r)<=0: break self.to.send(r) print('tran1 - ok') self.running=False except: self.running=False try: #self.to.close() self.to.shutdown(socket.SHUT_RDWR) except: print('to - err') def tran2(self): try: while self.running: print('tran2 - reading') r=self.to.recv(8192) print('tran2 - ' + str(len(r))) if len(r)<=0: break self.fr.send(r) print('tran2 - ok') self.running=False except: self.running=False try: #self.fr.close() self.fr.shutdown(socket.SHUT_RDWR) except: print('fr - err') def run(self): try: self.to.connect((server, toport)) #self.fr.settimeout(30) #self.to.settimeout(30) t1=threading.Thread(target=self.tran1) t2=threading.Thread(target=self.tran2) t1.start() t2.start() t1.join() t2.join() self.running=False try: self.fr.shutdown(socket.SHUT_RDWR) except: print('fr - err') try: self.to.shutdown(socket.SHUT_RDWR) except: print('to - err') except: return def main(): lst=[] print('listening') lfd=socket.socket(socket.AF_INET, socket.SOCK_STREAM) lfd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lfd.bind(('0.0.0.0', fromport)) lfd.listen(max_conn) while(True): conn_fd, addr=lfd.accept() print(addr) conn=TransConn(conn_fd) conn.start() lst.append(conn) if __name__=='__main__': main()
差不多能用。
发表评论