Jesse Burk
Jesse Burk

Reputation: 11

How do I send htm file to socket

I am trying to send this htm file to a web browser and have the browser display the contents of the file. When I run my code, all that happens is the browsers displays the name of the htm file and nothing else.

try 
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        String input = in.readLine();

        while (!input.isEmpty()) 
        {
            System.out.println("\tserver read a line: " + input);
            input = in.readLine();
        }

        System.out.println("");

        File myFile = new File ("hello.htm");

        out.println("HTTP/1.1 200 OK");
        out.println("Content-Type: text/html");
        out.println("\r\n");
        out.write(myFile);
        out.flush();
        out.close();
    }

    catch(Exception e)
    {
        System.out.println("\ncaught exeception: " + e + "\n");
    }

Upvotes: 0

Views: 61

Answers (1)

Raghav
Raghav

Reputation: 259

You need to actually write the contents of the file to the stream:

...
BufferedReader in2 = new BufferedReader(new FileReader(myFile));
out.write("HTTP/1.1 200 OK\r\n");
out.write("Content-Type: text/html\r\n");
//Tell the end user how much data you are sending
out.write("Content-Length: " + myFile.length() + "\r\n");
//Indicates end of headers
out.write("\r\n");
String line;
while((line = in2.readLine()) != null) {
    //Not sure if you should use out.println or out.write, play around with it.
    out.write(line + "\r\n");
}
//out.write(myFile); Remove this
out.flush();
out.close();
...

The above code is just an idea of what you really should be doing. It takes into account the HTTP protocol.

Upvotes: 1

Related Questions