Пожалуйста, помогите мне понять, что не так с этим кодом веб-прокси

Я хочу написать веб-прокси для упражнений, и этот код у меня есть:


// returns a map that contains the port and the host
def parseHostAndPort(String data) {
    def objMap // this has host and port as keys
    data.eachLine { line ->
        if(line =~ /^(?i)get|put|post|head|trace|delete/) {
            println line
            def components = line.split(" ")
            def resource = components[1]
            def colon = resource.indexOf(":")
            if(colon != -1) {
                URL u = new URL(resource)
                def pHost = u.host
                def pPort = u.port
                return (objMap = [host:pHost,port:pPort])
            }
            else {
                return (objMap = [host:resource,port:80])
            }
        }
    }
    return objMap
}

// reads a http request from a client
def readClientData(Socket clientSocket) {
    def actualBuffer = new StringBuilder()
    InputStream inStream = clientSocket.inputStream
    while(true) {
        def available = inStream.available()
        if(available == 0)
        break;
        println "available data $available"
        def buffer = new byte[available]
        def bytesRead = inStream.read(buffer,0,available)
        actualBuffer << new String(buffer)
    }
    return actualBuffer.toString()
}

def sock = new ServerSocket(9000)
sock.reuseAddress = true
while(true) {
    sock.accept { cli ->
        println "got a client"
        def data = readClientData(cli)
        def parsed = parseHostAndPort(data)
        def host = parsed["host"]
        def port = parsed["port"]

        println "got from client $data"

        def nsock = new Socket(host,port)
        nsock << data // send data received from client to the socket
        nsock.outputStream.flush() 
        def datax = readClientData(nsock)
        println "got back $datax"
        cli << datax // send the client the response
        cli.outputStream.flush()
        cli.close()
    }
}

Сейчас все, что он делает, это:

read the HTTP request my browser sends

parse the host and port

connect to that host, and write the data received from the client

send the client back the data received from the host

Но ... это не работает все время. Иногда он сделает хороший запрос, иногда нет. Я думаю, что это проблема буферизации, я не уверен. Дело в том, я добавилflush звонки, а еще ничего.

Можете ли вы определить, что я делаю неправильно?

РЕДАКТИРОВАТЬ:

I noticed that if I add some sleep calls, the proxy seems to "work" on a higher number of requests, but not all of them. to collect the bounty, help me find out what I'm doing wrong. What's the normal "algorithm" used for a web proxy? Where am I deviating from it? Thanks!

Ответы на вопрос(6)

Ваш ответ на вопрос