I'm new to coding and Java,I have create a simple client-server program where the client can request a file. Its content will be displayed in the browser page together with some details like the data type and the length. I'm now having a problem, I'm not sure how to display in the browser the server response for a correct connection like "HTTP/1.1 200 OK" and for the connection closed like "Connection: close". I have a method to handle the response as follow:
import java.io.*;
import java.net.*;
import java.util.*;
public class ReadRequest {
private final static int LISTENING_PORT = 50505;
protected static Socket client;
protected static PrintStream out;
static String requestedFile;
@SuppressWarnings("resource")
public static void main(String[] args) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(LISTENING_PORT);
}
catch (Exception e) {
System.out.println("Failed to create listening socket.");
return;
}
System.out.println("Listening on port " + LISTENING_PORT);
try {
while (true) {
Socket connection = serverSocket.accept();
System.out.println("\nConnection from "+ connection.getRemoteSocketAddress());
ConnectionThread thread = new ConnectionThread(connection);
thread.start();
}
}
catch (Exception e) {
System.out.println("Server socket shut down unexpectedly!");
System.out.println("Error: " + e);
System.out.println("Exiting.");
}
}
private static void handleConnection(Socket connection) {
String username = System.getProperty("user.name");
String httpRootDir = "C:\\Users\\"+(username)+"\\Downloads\\";
client = connection;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintStream (client.getOutputStream());
String line = null;
String req = null;
req = in.readLine();
line = req;
while (line.length() > 0)
{
line = in.readLine();
}
StringTokenizer st = new StringTokenizer(req);
if (!st.nextToken().equals("GET"))
{
sendErrorResponse(501);
return;
}
requestedFile = st.nextToken();
File f = new File(httpRootDir + requestedFile);
if (!f.canRead())
{
sendErrorResponse(404);
return;
}
sendResponseHeader(getMimeType(requestedFile),(int) f.length());
sendFile(f,client.getOutputStream());
}
catch (Exception e) {
System.out.println("Error while communicating with client: " + e);
}
finally {
try {
connection.close();
}
catch (Exception e) {
}
System.out.println("Connection closed.");
};
}
private static void sendResponseHeader(String type,int length)
{
out.println("Content-type: " +type+"\r\n");
out.println("Content-Length: " +length+"\r\n");
}
private static void sendErrorResponse(int errorCode)
{
switch(errorCode) {
case 404:
out.print("HTTP/1.1 404 Not Found");
out.println("Connection: close " );
out.println("Content-type: text/plain" +"\r\n");
out.println("<html><head><title>Error</title></head><body> <h2>Error: 404 Not Found</h2> <p>The resource that you requested does not exist on this server.</p> </body></html>");
break;
case 501:
out.print("HTTP/1.1 501 Not Implemented");
out.println("Connection: close " );
out.println("Content-type: text/plain" +"\r\n");
break;
}
}
private static String getMimeType(String fileName) {
int pos = fileName.lastIndexOf('.');
if (pos < 0)
return "g-application/x-unknown";
String ext = fileName.substring(pos+1).toLowerCase();
if (ext.equals("txt")) return "text/plain";
else if (ext.equals("html")) return "text/html";
else if (ext.equals("htm")) return "text/html";
else if (ext.equals("css")) return "text/css";
else if (ext.equals("js")) return "text/javascript";
else if (ext.equals("java")) return "text/x-java";
else if (ext.equals("jpeg")) return "image/jpeg";
else if (ext.equals("jpg")) return "image/jpeg";
else if (ext.equals("png")) return "image/png";
else if (ext.equals("gif")) return "image/gif";
else if (ext.equals("ico")) return "image/x-icon";
else if (ext.equals("class")) return "application/java-vm";
else if (ext.equals("jar")) return "application/java-archive";
else if (ext.equals("zip")) return "application/zip";
else if (ext.equals("xml")) return "application/xml";
else if (ext.equals("xhtml")) return"application/xhtml+xml";
else return "g-application/x-unknown";
}
private static void sendFile(File file, OutputStream socketOut) throws IOException {
try (InputStream infile = new BufferedInputStream(new FileInputStream(file))) {
OutputStream outfile = new BufferedOutputStream(socketOut);
while (true) {
int x = infile.read();
if (x < 0)
break;
outfile.write(x);
}
outfile.flush();
}
}
private static class ConnectionThread extends Thread {
Socket connection;
ConnectionThread(Socket connection) {
this.connection = connection;
}
public void run() {
handleConnection(connection);
}
}
}
Any suggestion on how I can do that? thank you