首页 > 编程 > Python > 正文

Python简单实现的代理服务器端口映射功能示例

2020-02-22 23:38:34
字体:
来源:转载
供稿:网友

本文实例讲述了Python简单实现的代理服务器端口映射功能。分享给大家供大家参考,具体如下:

一 代码

1、模拟服务端代码

import sysimport socketimport threading#回复消息,原样返回def replyMessage(conn):  while True:    data = conn.recv(1024)    conn.send(data)    if data.decode().lower() == 'bye':      break  conn.close()def main():  sockScr = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  sockScr.bind(('', port))  sockScr.listen(200)  while True:    try:      conn, addr = sockScr.accept()      #只允许特定主机访问本服务器      if addr[0] != onlyYou:        conn.close()        continue      #创建并启动线程      t = threading.Thread(target=replyMessage, args=(conn,))      t.start()    except:      print('error')if __name__ == '__main__':  try:    #获取命令行参数    port = int(sys.argv[1])    onlyYou = sys.argv[2]    main()  except:    print('Must give me a number as port')

2、模拟代理服务器代码

import sysimport socketimport threadingdef middle(conn, addr):  #面向服务器的Socket  sockDst = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  sockDst.connect((ipServer,portServer))  while True:    data = conn.recv(1024).decode()    print('收到客户端消息:'+data)    if data == '不要发给服务器':      conn.send('该消息已被代理服务器过滤'.encode())      print('该消息已过滤')    elif data.lower() == 'bye':      print(str(addr)+'客户端关闭连接')      break    else:      sockDst.send(data.encode())      print('已转发服务器')      data_fromServer = sockDst.recv(1024).decode()      print('收到服务器回复的消息:'+data_fromServer)      if data_fromServer == '不要发给客户端':        conn.send('该消息已被代理服务器修改'.encode())        print('消息已被篡改')      else:        conn.send(b'Server reply:'+data_fromServer.encode())        print('已转发服务器消息给客户端')  conn.close()  sockDst.close()def main():  sockScr = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  sockScr.bind(('', portScr))  sockScr.listen(200)  print('代理已启动')  while True:    try:      conn, addr = sockScr.accept()      t = threading.Thread(target=middle, args=(conn, addr))      t.start()      print('新客户:'+str(addr))    except:      passif __name__ == '__main__':  try:    #(本机IP地址,portScr)<==>(ipServer,portServer)    #代理服务器监听端口    portScr = int(sys.argv[1])    #服务器IP地址与端口号    ipServer = sys.argv[2]    portServer = int(sys.argv[3])    main()  except:    print('Sth error')

3、模拟客户端代码

import sysimport socketdef main():  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  sock.connect((ip, port))  while True:    data = input('What do you want to ask:')    sock.send(data.encode())    print(sock.recv(1024).decode())    if data.lower() == 'bye':      break  sock.close()if __name__ == '__main__':  try:    #代理服务器的IP地址和端口号    ip = sys.argv[1]    port = int(sys.argv[2])    main()  except:    print('Sth error')            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表