c=socket(AF_INET,SOCK_STREAM) #初始化套接字 c.connect(('127.0.0.1',6666)) #连接服务器 text=c.recv(1024) print(bytes.decode(text)) for i in range(10): data=input() c.send(str.encode(data)) c.close()
s = socket(AF_INET,SOCK_STREAM) s.bind(('localhost',6666)) s.listen(5) whileTrue: sock,addr = s.accept() print('Connected By',addr) whileTrue: cmd = sock.recv(1024) cmd = bytes.decode(cmd) if cmd == 'exit': print('TCPClient has lost') break result = os.popen(cmd).read() sock.send(str.encode(result))
客户端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from socket import *
HOST = '127.0.0.1' PORT = input('Please input a PORT to connect: ') PORT = int(PORT)
c = socket(AF_INET,SOCK_STREAM) c.connect((HOST,PORT)) text = c.recv(1024) print(bytes.decode(text)) whileTrue: cmd = input('Please input a command: ') c.send(str.encode(cmd)) if cmd == 'exit': c.close() break result = c.recv(1024) result = bytes.decode(result) print(result)
defServer(LPORT,CHOST,CPORT): c = Client(CHOST,CPORT) s = socket(AF_INET,SOCK_STREAM) s.bind(('localhost',LPORT)) s.listen(5) whileTrue: sock,addr = s.accept() print('Connected By',addr) sock.send(str.encode('Welcome to TCPProxy!')) whileTrue: cmd = sock.recv(1024) if bytes.decode(cmd) == 'exit': print('TCPClient '+addr+' has lost') Forward(c,cmd) c.close() break print('The command from TCPClient is: '+bytes.decode(cmd)) result = Forward(c,cmd) print('The result from TCPServer is: '+bytes.decode(result)) sock.send(result)
defServer(LPORT,CHOST,CPORT): c = Client(CHOST,CPORT) s = socket(AF_INET,SOCK_STREAM) s.bind(('localhost',LPORT)) s.listen(5) whileTrue: sock,addr = s.accept() print('Connected By',addr) sock.send(str.encode('Welcome to TCPProxy!')) whileTrue: cmd = sock.recv(1024) if bytes.decode(cmd) == 'exit': print('TCPClient '+addr+' has lost') Forward(c,cmd) c.close() break print('The command from TCPClient is: '+bytes.decode(cmd)) result = Forward(c,cmd) print('The result from TCPServer is: '+bytes.decode(result)) sock.send(result)
defClient(CHOST,CPORT): c = socket(AF_INET,SOCK_STREAM) c.connect((CHOST,CPORT)) return c
defForward(c,cmd): c.send(cmd) result = c.recv(1024) return result