网络代理服务器的设计与实现 python实现 计算机网络课程设计

妖精的绣舞 提交于 2020-01-18 01:09:06
import threading
import socket
import tkinter as tk
from tkinter import ttk

ip = '127.0.0.1'
port = 8030
i = 0



class MyProxy:
    def __init__(self, socket_client):
        while True:
            socket_client_conn, addr = socket_client.accept()
            t = threading.Thread(target=self.handler_conn, args=(socket_client_conn,))
            t.start()

    def handler_conn(self, socket_client_conn):
        data = socket_client_conn.recv(1024).decode()
        # print(data)
        head = None
        try:
            head = data.splitlines()[0].split()
        except:
            pass
        head_method = head[0]
        head_url = head[1]
        target_url = head_url.split(':')[0]
        host = head_url.replace('http://', '').split('/')[0].split(':')
        target_host = host[0]
        target_port = 80 if len(host) == 1 else host[1]

        print('target_url: {target_host}, target_port: {target_port}'.format(target_host=target_host,
                                                                             target_port=target_port))
        target_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        target_socket.settimeout(20)
        try:
            target_socket.connect((target_host, int(target_port)))
        except:
            pass
        if head_method == 'CONNECT':
            socket_client_conn.send(b"HTTP/1.1 200 Connection established\r\nConnection: close\r\n\r\n")
        else:

            target_socket.send(data.encode())

        # 开始线程处理返回来的数据
        t1 = threading.Thread(target=self.recv_data, args=(socket_client_conn, target_socket, False))
        t2 = threading.Thread(target=self.recv_data, args=(target_socket, socket_client_conn, True))
        t1.start()
        t2.start()

    def recv_data(self, recv_socket, send_socket, flag):
        """
        处理数据
        :param recv_socket: 接收数据socket
        :param send_socket: 发送数据socket
        :param flag: False:接收client数据,发送到服务器,True:接受server数据返回client
        :return:
        """

        try:
            while True:
                buf = recv_socket.recv(1024 * 4)
                send_socket.send(buf)
                if not buf:
                    break
        except:
            send_socket.close()
            recv_socket.close()
            return
        if flag:
            send_socket.close()
            recv_socket.close()


if __name__ == '__main__':
    port = 8083
    ip = '127.0.0.1'
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((ip, port))
    s.listen(128)

    myProxy = MyProxy(s)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!