多线程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 ="<html><title>Not found</title><h1>404 NotFound</h1></html>";
        }
        
        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";

    }
}
结果展示:



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("<h1>404</h1>",'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()

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


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值