简体   繁体   中英

simple java web server but no output

I was writing a simple java web server to help me understand the mechanism. But seems it doesn't work. it will print the request, but i can't get any response on the browser or the telnet client. Could you please help to explain why there is no response?

public Server() throws IOException {
    this.ss = new ServerSocket(this.PORT);
}

@Override
public void run() {

    while(true) {
        try {
            Socket cli = this.ss.accept();
            new Thread(new Hanlder(cli)).start();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}

class Hanlder implements Runnable {

    private Socket client = null;

    public Hanlder(Socket cli) {
        client = cli;
    }

    @Override
    public void run() {
        BufferedWriter bwriter;
        try {

            InputStreamReader input = new InputStreamReader(this.client.getInputStream());
            BufferedReader buf = new BufferedReader(input);
            String line = null;
            while( (line = buf.readLine()) != null ) {
                System.out.println(line);
            }

            bwriter = new BufferedWriter( new OutputStreamWriter(client.getOutputStream()));
            bwriter.write("HTTP/1.1 200 OK \n"
                    + "Hello, World");
            bwriter.flush();

            this.client.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}

You also need to supply Content-Type and Content-Length parameters in your headers.

Also in HTTP, you should terminate lines with \\r\\n , and terminate the header with \\r\\n\\r\\n .

Eg:

bwriter.write("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 3\r\n\r\nABC");
while( (line = buf.readLine()) != null ) {

This loop will exit when the end of a stream is encountered.

The end of the stream has not been encountered! The browser has just stopped sending data while it waits for a response from the server.

A blank line is (I think) what signals the end of an HTTP request. This way, an HTTP/1.1 client can send additional requests (after receiving the first response) to the same server without the overhead of opening a new connection.

(Your server will send the response, but only after your client has terminated the connection, which is perhaps a bit too late.)


EDIT What you need in your while loop is (for starters):

if (line.isEmpty()) {
    break;
}

But, the whole HTTP protocol really needs to be implemented. This is a big learning project you've undertaken. Enjoy!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM