Ram
Ram

Reputation: 1084

Communication between a Browser and Server written in java

I made a simple server written in java which simply sends the html code of an html file to any client that connects to it. It uses port 8008. The problem is when I use chrome to get this html via http://localhost:8008, it does not seem to work. What should I do for the two to communicate properly and for the browser to render the html page. I am using ServerSockets. Also, how can a web browser send information or request to the server? Any ways using the url? THanks!

    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(8008);
    } catch (IOException e) {
        System.err.println("Could not listen on port: 8008.");
        System.exit(1);
    }

    Socket clientSocket = null;;
    try {
        clientSocket = serverSocket.accept();   //This is the browser requesting for connection
    } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
    }

    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
    BufferedReader in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream() ) );

    out.println("Some HTML Code");  //The browser should be able to render the HTML Code sent

    out.close();
    in.close();
    clientSocket.close();
    serverSocket.close();

Upvotes: 0

Views: 2834

Answers (3)

SJuan76
SJuan76

Reputation: 24895

HTTP is not just HTML, there are some headers included, v.g.

 HTTP/1.0 200 

that must be transmitted by the server.

Check:

a) that the server is effectively receiving the request (log that the server is running and answering)

b) that the message that you are replying is a valid HTTP message that the browser will accept (HTTP is a connection protocol while HTML is a content protocol, you could send both HTML or GIF images through HTTP).

Look in Google for HTTP Message Format

Upvotes: 0

Venkat
Venkat

Reputation: 2634

The server you've developed is **not a web server**, right? The server you've developed **cannot handle HTTP requests**(used Sockets), but unfortunately the 

browsers would use protocols (say, HTTP) to access files over network

.

You're expecting the result through wrong process. I would say develop a client Java program, which should connect to the port you mentioned with your ServerSocket initialization.

Upvotes: 2

sudmong
sudmong

Reputation: 2036

try using TCPMON to check the request and response, should help you to narrow down troubleshooting.

Upvotes: 0

Related Questions