Communication between a browser and a server written in java

advertisements

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();


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.