多线程Web服务器的设计与实现(JAVA与PYTHON)
来源:互联网 发布:c语言编程简单的小游戏 编辑:程序博客网 时间:2024/04/30 00:31
内容相关:
1、 网络基本原理(如:HTTP协议、Web服务器、Socket、TCP、UDP等)
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 socketimport reimport threadingimport timeCRLF = "\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()
结果与上图类似,不上图了。
1 0
- 多线程Web服务器的设计与实现(JAVA与PYTHON)
- 简单web服务器的设计与实现
- 基于MYSQL的 网络游戏 多线程 数据库 服务器 设计与实现
- 基于LDAP 的Web 邮件服务器的设计与实现
- 基于ARM的嵌入式web服务器的设计与实现
- 微型嵌入式Web服务器的设计与实现
- 微型嵌入式Web服务器的设计与实现
- 基于java web的档案管理系统的设计与实现
- 基于java web的企业人事管理系统的设计与实现
- Java 多线程 爬虫程序(spider)设计与实现
- java web 项目 图书管理系统的设计与实现
- Java Web 模板代码生成器的设计与实现
- ftp 多线程下载的设计与实现
- ftp 多线程下载的设计与实现
- C++:多线程类库的设计与实现(一)
- C++:多线程类库的设计与实现(二)
- C++:多线程类库的设计与实现(三)
- C++:多线程类库的设计与实现(四)
- http请求返回302处理方案
- POJ1679 The Unique MST(次小生成树[Kruskal]+链式前向星or普通版本)
- MyBatis-Spring配置
- 面试问题相关
- 链表的应用---基数排序
- 多线程Web服务器的设计与实现(JAVA与PYTHON)
- wordpress服务器系统更换windows->linux
- Codeforces Round #381 (Div. 2) &&Codeforce_740
- ACM需要掌握的算法
- glog--介绍以及vs2010 vs2013 vs2015下编译
- DrawerLayout及自定义的实现
- 驱动烧写基础
- 函数之间的通信方式
- GreenDao3使用笔记