Why Chrome is not rendering the page which it gets from socket output stream? Java

Viewed 1735

Here is my code:

import java.net.*;
import java.io.*;

class Server
{
     public static void main(String args[])
     {
          try
          {
                ServerSocket svr = new ServerSocket(8900);
                System.out.println("waiting for request");
                Socket s = svr.accept();
                System.out.println("got a request");
                InputStream in = s.getInputStream();
                OutputStream out = s.getOutputStream();

                int x;
                byte data[]= new byte[1024];

                x = in.read(data);

                String response  = "<html><head><title>HTML content via java socket</title></head><body><h2>Hi! Every Body.</h2></body></html>";
                out.write(response.getBytes());
                out.flush();

                s.close();
                svr.close();
                System.out.println("closing all");
          }
          catch(Exception ex)
          {
                System.out.println("Err : " + ex);
          }
     }
}

Running it I hope to go to Chrome right this : 127.0.0.1:8900 and get nicely looking piece of html, but actually Chrome is saying the following :

This page isn’t working 127.0.0.1 sent an invalid response. ERR_INVALID_HTTP_RESPONSE.

Whereas my Server.java is running as I want it to. The console in Eclipse says nicely after connection :

waiting for request got a request closing all.

So I am very stuck. Help me to figure that out, please.

1 Answers
Related