日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python实现http/https代理服务器

發布時間:2024/1/1 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python实现http/https代理服务器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

代碼:

# encoding:utf-8 import socket import _threadclass Header:"""用于讀取和解析頭信息"""def __init__(self, conn):self._method = Noneheader = b''try:while 1:data = conn.recv(4096)header = b"%s%s" % (header, data)if header.endswith(b'\r\n\r\n') or (not data):breakexcept:passself._header = headerself.header_list = header.split(b'\r\n')self._host = Noneself._port = Nonedef get_method(self):"""獲取請求方式:return:"""if self._method is None:self._method = self._header[:self._header.index(b' ')]return self._methoddef get_host_info(self):"""獲取目標主機的ip和端口:return:"""if self._host is None:method = self.get_method()line = self.header_list[0].decode('utf8')if method == b"CONNECT":host = line.split(' ')[1]if ':' in host:host, port = host.split(':')else:port = 443else:for i in self.header_list:if i.startswith(b"Host:"):host = i.split(b" ")if len(host) < 2:continuehost = host[1].decode('utf8')breakelse:host = line.split('/')[2]if ':' in host:host, port = host.split(':')else:port = 80self._host = hostself._port = int(port)return self._host, self._port@propertydef data(self):"""返回頭部數據:return:"""return self._headerdef is_ssl(self):"""判斷是否為 https協議:return:"""if self.get_method() == b'CONNECT':return Truereturn Falsedef __repr__(self):return str(self._header.decode("utf8"))def communicate(sock1, sock2):"""socket之間的數據交換:param sock1::param sock2::return:"""try:while 1:data = sock1.recv(1024)if not data:returnsock2.sendall(data)except:passdef handle(client):"""處理連接進來的客戶端:param client::return:"""timeout = 60client.settimeout(timeout)header = Header(client)if not header.data:client.close()returnprint(*header.get_host_info(), header.get_method())server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)try:server.connect(header.get_host_info())server.settimeout(timeout)if header.is_ssl():data = b"HTTP/1.0 200 Connection Established\r\n\r\n"client.sendall(data)_thread.start_new_thread(communicate, (client, server))else:server.sendall(header.data)communicate(server, client)except:server.close()client.close()def serve(ip, port):"""代理服務:param ip::param port::return:"""s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)s.bind((ip, port))s.listen(10)print('proxy start...')while True:conn, addr = s.accept()_thread.start_new_thread(handle, (conn,))if __name__ == '__main__':IP = "127.0.0.1"PORT = 8080serve(IP, PORT)

?

總結

以上是生活随笔為你收集整理的python实现http/https代理服务器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。