I just written a small program to test something, as below:
public class Main {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket clientSocket = null;
DataInputStream dataInputStream= null;
BufferedWriter bufferedWriter = null;
String line ;
try {
serverSocket = new ServerSocket(80);
clientSocket = serverSocket.accept();
dataInputStream = new DataInputStream(clientSocket.getInputStream());
while((line = dataInputStream.readLine()) != null){
System.out.println(line);
}
bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
bufferedWriter.write("HTTP/1.0 200 OK \n Date: Fri, 31 Dec 1999 23:59:59 GMT \n Content-Type: text/html \n Content-Length: 1354 \n <html>abcde<html/>");
bufferedWriter.flush();
} catch (IOException e) {
System.out.println("socket port cannot be opened.");
e.printStackTrace();
} finally{
try {
serverSocket.close();
bufferedWriter.close();
} catch (IOException e) {
System.out.println("socket port cannot be closed.");
e.printStackTrace();
}
}
}
}
I found the http response format from the internet, it should be correct. The problem is my browser keep on waiting for the response data (determine from the spinning logo), but the data is not returned successful. What mistake I have made?
I connect to the Java program by typing "localhost" in the browser, I can print out the request string in Java program but only fail to send back the response.