您好,登錄后才能下訂單哦!
這期內(nèi)容當中小編將會給大家?guī)碛嘘PPython中怎么實現(xiàn)代理服務器,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
這里就是使用Python簡單的實現(xiàn)一個二級代理。
#coding=utf-8 import socket import select import sys import threading import time import logging import os logsDir = "logs" if not os.path.isdir(logsDir): os.mkdir(logsDir) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='logs/logs.log', filemode='a') #C的IP和端口 to_addr = ('127.0.0.1', 8087) maxConnetions = 32 class Proxy: def __init__(self, addr): self.proxy = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.proxy.bind(addr) self.proxy.listen(maxConnetions) self.inputs = {self.proxy:None} self.route = {} def serve_forever(self): logging.info('proxy listen...') while 1: readable, _, _ = select.select(list(self.inputs.keys()), [], []) for self.sock in readable: if self.sock == self.proxy: self.on_join() else: try: data = self.sock.recv(8192) except Exception, e: logging.error(str(e)) self.on_quit() continue if not data: self.on_quit() else: try: self.route[self.sock].send(data) except Exception, e: logging.error(str(e)) self.on_quit() continue def on_join(self): client, addr = self.proxy.accept() logging.info("proxy client " + str(addr) + 'connect') forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: forward.connect(to_addr) except Exception, e: logging.error(str(e)) client.close() return self.inputs [client] = None self.inputs [forward] = None self.route[client] = forward self.route[forward] = client #刪除連接 def on_quit(self): ls = [self.sock] if self.sock in self.route: ls.append(self.route[self.sock]) for s in ls: if s in self.inputs: del self.inputs[s] if s in self.route: del self.route[s] s.close() if __name__ == "__main__": try: Proxy(('', 8192)).serve_forever() except KeyboardInterrupt, e: logging.error("KeyboardInterrupt" + str(e))
上述就是小編為大家分享的Python中怎么實現(xiàn)代理服務器了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。