2

I'm trying to create a simple server that accepts a request, and then writes the content of a file to the browser that sent the request. The server connects and writes to the socket. However my browser says

no data received

and doesn't display anything.

public class Main {

/**
 * @param args
 */
public static void main(String[] args) throws IOException{

    while(true){
        ServerSocket serverSock = new ServerSocket(6789);
        Socket sock = serverSock.accept();

        System.out.println("connected");

        InputStream sis = sock.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(sis));
        String request = br.readLine(); // Now you get GET index.html HTTP/1.1`
        String[] requestParam = request.split(" ");
        String path = requestParam[1];

        System.out.println(path);

        PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
        File file = new File(path);
        BufferedReader bfr = null;
        String s = "Hi";

        if (!file.exists() || !file.isFile()) {
            System.out.println("writing not found...");
             out.write("HTTP/1.0 200 OK\r\n");
             out.write(new Date() + "\r\n");
             out.write("Content-Type: text/html");
             out.write("Content length: " + s.length() + "\r\n");
             out.write(s);
        }else{
            FileReader fr = new FileReader(file);
            bfr = new BufferedReader(fr);
            String line;
            while ((line = bfr.readLine()) != null) {
                out.write(line);
            }
        }
        if(bfr != null){
            bfr.close();
        }
        br.close();
        out.close();
        serverSock.close();
    }
}

}
Beryllium
  • 12,808
  • 10
  • 56
  • 86

1 Answers1

0

Your code works for me (data shows up in the browser), if I use

http://localhost:6789/etc/hosts

and there is a file /etc/hosts (Linux filesystem notation).


If the file does not exist, this snippet

out.write("HTTP/1.0 200 OK\r\n");
out.write(new Date() + "\r\n");
out.write("Content-Type: text/html\r\n");
out.write("\r\n");
out.write("File " + file + " not found\r\n");
out.flush();

will return data that shows up in the browser: Note that I have explicitly added a call to flush() here. Make sure that out is flushed in the other case as well.

The other possibility is to reorder your close statements. A quote from EJP's answer on How to close a socket:

You should close the outermost output stream you have created from the socket. That will flush it.

This is especially the case if the outermost output stream is (another quote from the same source):

a buffered output stream, or a stream wrapped around one. If you don't close that, it won't be flushed.

So out.close() should be called before br.close().

Community
  • 1
  • 1
Beryllium
  • 12,808
  • 10
  • 56
  • 86