views:

189

answers:

1

I want to write a simple web proxy, for exercise. Here's the code I have so far:


def g = new Proxy()
g.serverPort = 9000
println "starting"
g.eachClient { Socket client ->
    println "got a client"
    try {
        client.withStreams { input,output ->
            String text = input.text
            println "received $text from client"
            client.close()
        }
    } catch(IOException io) {
        println "IO error. Probably client disconnected"
        //io.printStackTrace()
    }
}

the thing is, the line :

String text = input.text

consumes all the available data in the Socket's InputStream. If the client isn't closing the connection, that method will just wait until it can read a end of file character ( if I remember correctly ). What do I have to prevent this from happening, and have the client's string available ASAP?

+2  A: 

I think you'll want to check the documentation on ObjectInputStream. Do length = input.available to get the number of available bytes at the present time, then use input.read(buffer, offset, length) to read in exactly as many bytes are available. You'll probably want to launch a new thread for every new connection which transparently manages this buffer in the background, unless you're making a single-threaded proxy to begin with.

Conspicuous Compiler
This worked! Thanks! One more question please, how does java know how many bytes are available?
Geo
That's more a question of the underlying operating system's socket library, which Java abstracts away for you. You can see an example of how to do this using C in a *nix operating system here: http://www.dholm.com/2008/05/13/available-socket-bytes/
Conspicuous Compiler