Tutorial 11 - Socket Programming Part 2
Tutorial 11 - Socket Programming Part 2
Contents
1
Objectives .................................................................................................................................................... 1
Question ...................................................................................................................................................... 2
1 Objectives
In this session we want to develop a simple web server.
2 Source code1
public class Web {
public static void main(String[] args) throws Exception {
String requestMessageLine;
String fileName;
ServerSocket listenSocket = new ServerSocket(88);
Socket connectionSocket = listenSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
requestMessageLine = inFromClient.readLine();
StringTokenizer tokenizedLine = new StringTokenizer(requestMessageLine);
if (tokenizedLine.nextToken().equals("GET")) {
fileName = tokenizedLine.nextToken();
if (fileName.startsWith("/") == true) {
fileName = fileName.substring(1);
}
File file = new File(fileName);
int numOfBytes = (int) file.length();
FileInputStream inFile = new FileInputStream(fileName);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);
outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n");
if (fileName.endsWith(".jpg")) {
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
}
if (fileName.endsWith(".gif")) {
outToClient.writeBytes("Content-Type: image/gif\r\n");
}
if (fileName.endsWith(".html")) {
outToClient.writeBytes("Content-Type: text/HTML\r\n");
}
outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
outToClient.writeBytes("\r\n");
outToClient.write(fileInBytes, 0, numOfBytes);
connectionSocket.close();
} else {
System.out.println("Bad Request Message");
}
1
3 How to test?
We need to make sure this application is able to response to our request, how to test this simple web
server?
5 Question
In the real world, is a web server same as UDP socket application? Please illustrate your answer.
References
-