Java 实现 web服务器的简单实例
实例代码:
import java.util.*; // Chapter 8, Listing 3 public class WebServerDemo { // Directory of HTML pages and other files protected String docroot; // Port number of web server protected int port; // Socket for the web server protected ServerSocket ss; // Handler for a HTTP request class Handler extends Thread { protected Socket socket; protected PrintWriter pw; protected BufferedOutputStream bos; protected BufferedReader br; protected File docroot; public Handler(Socket _socket, String _docroot) throws Exception { socket = _socket; // Get the absolute directory of the filepath docroot = new File(_docroot).getCanonicalFile(); } public void run() { try { // Prepare our readers and writers br = new BufferedReader(new InputStreamReader( socket.getInputStream())); bos = new BufferedOutputStream(socket.getOutputStream()); pw = new PrintWriter(new OutputStreamWriter(bos)); // Read HTTP request from user (hopefully GET /file...... ) String line = br.readLine(); // Shutdown any further input socket.shutdownInput(); if (line == null) { socket.close(); return; } if (line.toUpperCase().startsWith("GET")) { // Eliminate any trailing " "); tokens.nextToken(); String req = tokens.nextToken(); // If a path character / or / is not present, add it to the // document root // and then add the file request, to form a full filename String name; if (req.startsWith("/") || req.startsWith("//")) name = this.docroot + req; else name = this.docroot + File.separator + req; // Get absolute file path File file = new File(name).getCanonicalFile(); // Check to see if request doesn't start with our document // root .... if (!file.getAbsolutePath().startsWith( this.docroot.getAbsolutePath())) { pw.println("HTTP/1.0 403 Forbidden"); pw.println(); } // ... if it's missing ..... else if (!file.exists()) { pw.println("HTTP/1.0 404 File Not Found"); pw.println(); } // ... if it can't be read for security reasons .... else if (!file.canRead()) { pw.println("HTTP/1.0 403 Forbidden"); pw.println(); } // ... if its actually a directory, and not a file .... else if (file.isDirectory()) { sendDir(bos, pw, file, req); } // ... or if it's really a file else { sendFile(bos, pw, file.getAbsolutePath()); } } // If not a GET request, the server will not support it else { pw.println("HTTP/1.0 501 Not Implemented"); pw.println(); } pw.flush(); bos.flush(); } catch (Exception e) { e.printStackTrace(); } try { socket.close(); } catch (Exception e) { e.printStackTrace(); } } protected void sendFile(BufferedOutputStream bos, PrintWriter pw, String filename) throws Exception { try { java.io.BufferedInputStream bis = new java.io.BufferedInputStream( new FileInputStream(filename)); byte[] data = new byte[10 * 1024]; int read = bis.read(data); pw.println("HTTP/1.0 200 Okay"); pw.println(); pw.flush(); bos.flush(); while (read != -1) { bos.write(data, 0, read); read = bis.read(data); } bos.flush(); } catch (Exception e) { pw.flush(); bos.flush(); } } protected void sendDir(BufferedOutputStream bos, PrintWriter pw, File dir, String req) throws Exception { try { pw.println("HTTP/1.0 200 Okay"); pw.println(); pw.flush(); pw.print("<html><head><title>Directory of "); pw.print(req); pw.print("</title></head><body><h1>Directory of "); pw.print(req); pw.println("</h1><table border=/"0/">"); File[] contents = dir.listFiles(); for (int i = 0; i < contents.length; i++) { pw.print("<tr>"); pw.print("<td><a href="/" rel="external nofollow" rel="external nofollow" mce_href="/" rel="external nofollow" rel="external nofollow" ""); pw.print(req); pw.print(contents[i].getName()); if (contents[i].isDirectory()) pw.print("/"); pw.print("/">"); if (contents[i].isDirectory()) pw.print("Dir -> "); pw.print(contents[i].getName()); pw.print("</a></td>"); pw.println("</tr>"); } pw.println("</table></body></html>"); pw.flush(); } catch (Exception e) { pw.flush(); bos.flush(); } } } // Check that a filepath has been specified and a port number protected void parseParams(String[] args) throws Exception { switch (args.length) { case 1: case 0: System.err.println("Syntax: <jvm> " + this.getClass().getName() + " docroot port"); System.exit(0); default: this.docroot = args[0]; this.port = Integer.parseInt(args[1]); break; } } public WebServerDemo(String[] args) throws Exception { System.out.println("Checking for paramters"); // Check for command line parameters parseParams(args); System.out.print("Starting web server...... "); // Create a new server socket this.ss = new ServerSocket(this.port); System.out.println("OK"); for (;;) { // Accept a new socket connection from our server socket Socket accept = ss.accept(); // Start a new handler instance to process the request new Handler(accept, docroot).start(); } } // Start an instance of the web server running public static void main(String[] args) throws Exception { WebServerDemo webServerDemo = new WebServerDemo(args); } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
暂无评论...
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
2024年11月23日
2024年11月23日
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]