菜鷄日記——Computer Networking: Exp.1 Implement a Simple Web Server with Java on Windows

Targets

  1. Receive and analyze HTTP requests.
  2. Find the requested files on the server.
  3. Create response messages including requested files.
  4. Transfer response messages to client.

Steps

  1. Install Java SDK on Windows.
  2. Implement Web server with Java language.
  3. Start the Web server.
  4. Test the Web server.

Result

Step 1: To avoid repetition, it's not described here. 

Step 2: Implement a simple multi-threaded Web server with Java.

(Reference: https://www.cnblogs.com/chenpi/p/5602171.html)

  1. Create a ServerSocket object.
  2. Call the accept() of the ServerSocket object to wait for connection from client, return a Socket object if is connected.
  3. Get InputStream and OutputStream from the Socket object.
  4. Read the request message from  the InputStream and then analyze it (get the URL of the requested file).
  5. Find the requested file and then create a response which will be wrote to the OutputStream.
  6. Close the soket to ends the connection between the server and the client.
  7. Jump to 2, repeat this process.
import java.io.*;
import java.net.*;
import java.util.*;

public final class WebServer {
    public static void main(String args[]) throws Exception {
        // Set port number and establish a listen socket in server with the port.
        int port = 8080;
        ServerSocket serverSocket = new ServerSocket(port);
		
        // Process HTTP service requests in an infinite loop.
        while (true) {
            // Listen for a TCP connection request.
            Socket socket = serverSocket.accept();
			
            // Process the request in a new thread.
            HttpRequest request = new HttpRequest(socket);
            Thread thread = new Thread(request);
            thread.start();

            //insert socket.close() here will cause exception
        }
    }
}
import java.io.*;
import java.net.*;
import java.util.*;


final class HttpRequest implements Runnable {	// Implements the Runnable interface so that requests can be processed in different threads.
    final static String CRLF = "\r\n";
    final static int BUFFER_SIZE = 1024;
	
    Socket socket;
	
    // Constructor
    public HttpRequest(Socket socket) {
        this.socket = socket;
    }
	
    // Implement the run() method of the Runnable interface.
    public void run() {
        try {
            processRequest();
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
	
    private void processRequest() throws Exception {
        // Get a reference to the socket's input and output streams.
        InputStream is = socket.getInputStream();
        DataOutputStream os = new DataOutputStream(socket.getOutputStream());
		
        // Set up input stream filters.
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
		
        // Get the URL information.
        String requestLine = br.readLine();
        StringTokenizer tokens = new StringTokenizer(requestLine);
        tokens.nextToken();		// skip over the method of request line, which should be "GET" and at the head of the line
        String URL = tokens.nextToken();	
        URL = "./WEB_APPS/" + URL;
		
        // Attempt to find the requested file.
        FileInputStream fis = null;
        boolean fileExists = true;
        try {
            fis = new FileInputStream(URL);
        }
        catch (FileNotFoundException e) {
            fileExists = false;
        }
		
        // Display the whole request message on the CMD window.
        System.out.println();
        System.out.println(requestLine);
        String headerLine = null;
        while ((headerLine = br.readLine()).length() != 0) {
            System.out.println(headerLine);
        }
		
        String statusLine = null;
        String contentTypeLine = null;
        String entityBody = null;
      
        if (fileExists) {
            statusLine = "HTTP/1.1 200 OK" + CRLF;
            contentTypeLine = "Content-Type: " + getContentType(URL) + CRLF;
        }
        else {
            statusLine = "HTTP/1.1 404 Not Found" + CRLF;
            contentTypeLine = "Content-Type: text/html" + CRLF;
            entityBody = "<HTML><HEAD><TITLE>Not Found</TITLE></HEAD><BODY>Not Found</BODY></HTML>";
        }
		
        // Response the request.
        os.writeBytes(statusLine);	// method writeBytes() is implemented in class DataOutputStream
        os.writeBytes(contentTypeLine);
        os.writeBytes(CRLF);
        if (fileExists) {
            sendBytes(fis, os);
            fis.close();
        }
        else
            os.writeBytes(entityBody);
		
        is.close();
        os.close();
        br.close();
        socket.close();
    }
	
    private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytes = 0;
		
        while ((bytes = fis.read(buffer)) != -1)
        os.write(buffer, 0, bytes);
    }

    private static String getContentType(String URL) {
        if(URL.endsWith(".htm") || URL.endsWith(".html"))
            return "text/html";

        if(URL.endsWith(".ram") || URL.endsWith(".ra"))
            return "audio/x-pn-realaudio";
		
        return "application/octet-stream" ;
    }
}

Step 3: Use "javac" command to compile, and use "java" command to start the Web server.

javac WebServer.java

java WebServer

Step 4: Type the URL in the browser's address bar to test the Web server.

Requests from client showed on CMD window:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值