多线程Web服务器的设计与实现(JAVA与PYTHON)

内容相关:

1、 网络基本原理(如:HTTP协议、Web服务器、SocketTCPUDP等)

2、 网络服务器基本配置(简单C/S网络的组建、web服务器的基本配置等)

3、程序设计(socket编程、多线程程序设计等)

JAVA代码:

MultiThreadWebServer.java

import java.net.* ;

public final class MultiThreadWebServer {
    public static void main(String argv[]) throws Exception {
    	
    	ServerSocket socket = new ServerSocket(8900);
        while (true) {
	    // Listen for a TCP connection request.
	    Socket connection = socket.accept();

	    HttpRequest request = new HttpRequest(connection);
	    
	    Thread thread = new Thread(request);

	    thread.start();
        }
    }
}

HttpRequest.java

import java.io.* ;
import java.net.* ;
import java.util.* ;

final class HttpRequest implements Runnable {

    final static String CRLF = "\r\n";
    Socket socket;
    
    public HttpRequest(Socket socket) throws Exception {
        this.socket=socket;
    }    
    
    public void run() {
	try {
	    	processRequest();
		} catch (Exception e) {
			System.out.println(e);
		}
    }

    private void processRequest() throws Exception {
    	InputStreamReader is=new InputStreamReader(socket.getInputStream());
        DataOutputStream os=new  DataOutputStream(socket.getOutputStream());
	    BufferedReader br = new BufferedReader(is);

        String  requestLine;
	    requestLine=br.readLine();
	    System.out.println(requestLine);

		String headerLine = null;
		while ((headerLine = br.readLine()).length() != 0) {
		        System.out.println(headerLine);
		}

		//Openfile
        StringTokenizer tokens = new StringTokenizer(requestLine);
        tokens.nextToken();  
        String fileName = tokens.nextToken();
        fileName="."+fileName;
	
        FileInputStream fis = null ;
        boolean fileExists = true ;
        try {
        	fis = new FileInputStream(fileName);
        } catch (FileNotFoundException e) {
        	fileExists = false ;
        }

        // Reponse
        String statusLine = null;        //状态行
        String contentTypeLine = null;   //Content-Type行
        String entityBody = null;        //Entity body部分
        if (fileExists) {
        	statusLine="HTTP/1.1 200 OK"+CRLF;
        	contentTypeLine = "Content-type: " + contentType( fileName ) + CRLF;
              
        } else {
        	statusLine="HTTP/1.1 404 NotFound"+CRLF;
        	contentTypeLine = "Content-type: text/html"+CRLF;
        	entityBody ="Not found

404 NotFound

"; } os.writeBytes(statusLine); os.writeBytes(contentTypeLine); os.writeBytes(CRLF); if (fileExists) { sendBytes(fis, os); fis.close(); } else { os.writeBytes(entityBody); } System.out.println(); os.close(); br.close(); socket.close(); } private static void sendBytes(FileInputStream fis,OutputStream os) throws Exception { byte[] buffer = new byte[1024]; int bytes=0; while((bytes=fis.read(buffer))!=-1){ os.write(buffer,0,bytes); } } private static String contentType(String fileName) { if(fileName.endsWith(".htm") || fileName.endsWith(".html")|| fileName.endsWith(".txt")) { return "text/html"; } if(fileName.endsWith(".jpg")) { return "image/jpeg"; } if(fileName.endsWith(".gif")) { return "image/gif"; } return "application/octet-stream"; } }
结果展示:

多线程Web服务器的设计与实现(JAVA与PYTHON)_第1张图片多线程Web服务器的设计与实现(JAVA与PYTHON)_第2张图片
多线程Web服务器的设计与实现(JAVA与PYTHON)_第3张图片

PYTHON代码(请在python3下运行):

import socket
import re
import threading
import time
CRLF = "\r\n"
contentTypeLine="Content-type:";
def server(conn,addr):
    data = conn.recv(2048)
    print(data)
    print("-----------\n")
    
    f = data.decode('utf-8').split(' ')[1]
    try:
        x=open('.'+f,"rb").read()
        conn.send(bytearray("HTTP/1.1 200 OK"+CRLF,'utf8'))
        conn.send(bytearray(contentTypeLine+webtype(f)+CRLF,'utf8'))
        conn.send(bytearray("Date:"+ time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) +CRLF,'utf8'))
        conn.send(bytearray(CRLF,'utf8'))
        conn.send(x)
        except IOError:
        conn.send(bytearray("HTTP/1.1 404 NotFound"+CRLF,'utf8'))
        conn.send(bytearray(contentTypeLine+"text/html"+CRLF,'utf8'))
        conn.send(bytearray("Date:"+ time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) +CRLF,'utf8'))
        conn.send(bytearray(CRLF,'utf8'))
        conn.send(bytes("

404

",'utf8')) conn.close() def webtype(filename): a=filename.split('.')[1] if a == 'txt': return 'text/html' if a == 'jpg': return 'image/jpeg' return "other type" if __name__ =='__main__': ip_port = ('127.0.0.1',8888) web = socket.socket() web.bind(ip_port) web.listen(5) print ('opening...PORT:8888') while True: conn,addr = web.accept() thread = threading.Thread(target=server, args=(conn, addr)) thread.start()

结果与上图类似,不上图了。


你可能感兴趣的:(python)