[Computer Network] Socket Programming Assignment 4: Proxy Proxy Server to improve the requirements -POST

Porxy Server


The basic requirements of this operation, reference may be: https://blog.csdn.net/young_cr7/article/details/104703586

  1. Introduce the principle of

    (1) POST request is typically used to send data to the server, and the proxy server may be sent by the client data cache. If there is history data for comparison , both the need to send the same data to the server (here assumed that the client sends a POST request, the proxy server to reach the server, the server is the only way to obtain the data). Both do not match, or no historical data exists when, by the proxy server sends a POST request to the server via the data mode, while the data cache. When data is transmitted successfully, the client sends a response to the message "OK"

    (2) server using a POST request may be written in the Python flask

    from flask import Flask, request
    app = Flask(__name__)
    
    
    @app.route('/simulator/gridConnect/', methods=['GET', 'POST'])
    def set_grid_connect():
        recv_data = request.get_json()
        print(request)
        if recv_data:
            grid_connect = recv_data['grid_connected']
        return "OK"
    

    (3) may send a request to the proxy server by means of POST software Postman

  2. Source code

from socket import *
import traceback

tcpSerSock = socket(AF_INET, SOCK_STREAM)
server_port = 22500
tcpSerSock.bind(('', server_port))
tcpSerSock.listen(1)

while True:
    print('Ready to serve...')
    tcpCliSock, addr = tcpSerSock.accept()
    print('Received a connection from:', addr)
    message = tcpCliSock.recv(1024).decode(encoding="utf-8")
    print(message)
    request_method = message.split()[0]
    # Extract the filename from the given message
    filename = message.split()[1].partition("//")[2].replace('/', '_').replace(':', '_')
    print(filename)
    fileExist = "false"
    if request_method == "GET":
        # 省略
    elif request_method == "POST":
        try:
            post_data = ''.join(message[message.index('{') + 1:message.index('}')].split())
            print(post_data)
            f = open(filename, "r")
            outputdata = f.read()
            print(outputdata)
            if post_data != outputdata:
                raise ValueError
            tcpCliSock.sendall("HTTP/1.1 200 OK\r\n".encode(encoding="utf-8"))
            tcpCliSock.sendall("Content-Type:text/html\r\n".encode(encoding="utf-8"))
            tcpCliSock.sendall("\r\nOK\r\n".encode(encoding="utf-8"))
            print('Not modified')
        except IOError:
            print(traceback.format_exc())
            tmpFile = open("./" + filename, "w")
            tmpFile.writelines(post_data)
            tmpFile.close()
            c = socket(AF_INET, SOCK_STREAM)
            host_address = message.split()[1].partition("//")[2].partition("/")[0].replace("www.", "", 1)
            hostname = host_address.partition(":")[0]
            host_port = int(host_address.partition(":")[2])
            try:
                c.connect((hostname, host_port))
                old_url = message.split()[1]
                new_url = ''.join(old_url.partition("//")[2].partition("/")[1:])
                message = message.replace(old_url, new_url)
                c.send(message.encode(encoding="utf-8"))
                buff = c.recv(1024).decode(encoding="utf-8")
                print(buff)
                tcpCliSock.send("HTTP/1.1 200 OK\r\n".encode(encoding="utf-8"))
                tcpCliSock.send("Content-Type:text/html\r\n".encode(encoding="utf-8"))
                tcpCliSock.send("\r\nOK\r\n".encode(encoding="utf-8"))
            except:
                print("Illegal request")
    tcpCliSock.close()
tcpSerSock.close()

  1. The client
    Here Insert Picture Description
    sends the server grid_connectedthe data (data format json), the response packet isOK

  2. Proxy Server

    (1) the data is not cached the proxy server transmits a POST request to the server

    POST http://localhost:9000/simulator/gridConnect/ HTTP/1.1
    Content-Type: application/json
    User-Agent: PostmanRuntime/7.22.0
    Accept: */*
    Cache-Control: no-cache
    Postman-Token: 39ae1a6d-1547-4ce6-afbe-b29d2eff9a06
    Host: localhost:9000
    Accept-Encoding: gzip, deflate, br
    Content-Length: 35
    Connection: keep-alive
    
    {
        "grid_connected": true	
    }
    
    localhost_9000_simulator_gridConnect_
    "grid_connected":true
    Traceback (most recent call last):
      File "D:/Pycharm-project/Computer Network/Socket/Proxy Server/proxyServer.py", line 61, in <module>
        f = open(filename, "r")
    FileNotFoundError: [Errno 2] No such file or directory: 'localhost_9000_simulator_gridConnect_'
    
    HTTP/1.0 200 OK
    

    (2) With the proxy server to cache the data, when the client sends data is consistent with the historical data, the print server proxy Not modified, the server sends a request to no longer

    POST http://localhost:9000/simulator/gridConnect/ HTTP/1.1
    Content-Type: application/json
    User-Agent: PostmanRuntime/7.22.0
    Accept: */*
    Cache-Control: no-cache
    Postman-Token: 6347322c-7f21-4c82-9866-a71a7ace662d
    Host: localhost:9000
    Accept-Encoding: gzip, deflate, br
    Content-Length: 35
    Connection: keep-alive
    
    {
        "grid_connected": true	
    }
    
    localhost_9000_simulator_gridConnect_
    "grid_connected":true
    "grid_connected":true
    Not modified
    

Published 27 original articles · won praise 0 · Views 394

Guess you like

Origin blog.csdn.net/young_cr7/article/details/104704237