I created a Java webserver that should send clients webpage files when the server's IP address is searched on their browsers. The problem is that I can only send an HTML file but I need to send CSS and also images that is embedded in the HTML file. Although I already linked the HTML file to an external CSS code and images, the CSS and images weren't displayed. I was at least able to get the CSS working because I inserted all the CSS codes directly in the HTML code. I am looking to find a way that enables the images to be displayed in the client's browser and if possible, also a way to send the external CSS code so I don't need to write CSS codes directly into HTML files in the future. It would be great if you could show the codes to fix the problem.
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. The Worker class handles each output to each clients.
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");
out.flush();
out.close();
client.close();
} catch(Exception e) {
System.out.println(e);
}
}
}