Search code examples
javahtmlmultithreadingsocketswebserver

How can I send a html file from the server to be opened in the client's browser?


I created a functioning web server and at the moment, I have to fully paste the html codes from the file into the server program for the client's browser to read the html code. I'd like an easier way where I could make a variable that leads to the html file in the server directory so the server can send whatever code is written in that file.

This is my main Server class:

package myserver.pkg1.pkg0;

import java.net.*;

public class Server implements Runnable {

    protected boolean isStopped = false;
    protected static ServerSocket server = null;

    public static void main(String[] args) {

        try {

            server = new ServerSocket(9000);
            System.out.println("Server is ON and listening for incoming requests...");
            Thread t1 = new Thread(new Server());
            t1.start();

        } catch(Exception e) {
            System.out.println("Could not open port 9000.\n" + e);
        }

    }

    @Override
    public void run() {

        while(!isStopped) {

            try {
                Socket client = server.accept();
                System.out.println(client.getRemoteSocketAddress() + " has connected.");
                Thread t2 = new Thread(new Server());
                t2.start();
                new Thread(new Worker(client)).start();
            } catch(Exception e) {
                System.out.println(e);
            }

        }

    }

}

As you can see after the server accepts request, the client socket variable is forwarded to a new class Worker.

This is Worker class:

package myserver.pkg1.pkg0;

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

public class Worker implements Runnable {

    protected Socket client;

    public Worker(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {

        try {
            PrintWriter out = new PrintWriter(client.getOutputStream());       
            out.println("HTTP/1.1 200 OK");
            out.println("Content-type: text/html");
            out.println("\r\n");
            //In this line I used out.println("full html code"); but I'd like a simpler way where it can search for the html file in the directory and send it.
            out.flush();
            out.close();
            client.close();

        } catch(Exception e) {
            System.out.println(e);
        }

    }

}

The Worker class handles all the output where it will be seen on the client's browser and I'd like it to be the outcome of the html file.


Solution

  • You can place a file "index.html" in your classpath and do

        InputStream in = this.getClass().getClassLoader()
                .getResourceAsStream("index.html");
        String s = new BufferedReader(new InputStreamReader(in))
                .lines().collect(Collectors.joining("\n"));
        out.println(s);