📄 httpd.java
字号:
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
/**
* 一个简单的Web服务器实例
* 没有考虑安全,没有配置管理,不支持CGI和Servlets
* 此版本是多线程的,I/O处理在Handler类当中实现
**/
public class Httpd {
/** Web服务器的缺省服务断口 */
public static final int HTTP = 80;
/** 用来接受客户端连接的服务器端Socket */
protected ServerSocket sock;
/** 用于读取Web服务器的配置信息 */
protected Properties wsp;
/** 用于读取Web服务器的MIMI类型信息 */
protected Properties mimeTypes;
/** Web服务器的根目录 */
protected String rootDir;
public static void main(String argv[]) {
System.out.println("Our JavaWeb Server 0.1 starting...");
Httpd w = new Httpd();
// 解析命令行参数,在制定端口启动Web服务器
if (argv.length == 2 && argv[0].equals("-p")) {
w.startServer(Integer.parseInt(argv[1]));
} else {
w.startServer(HTTP);// 在缺省端口启动Web服务器
}
// 开始监听服务端口,等待用户连接
w.runServer();
}
/** 此Web服务器的主要功能函数. 每有一个客户端连接
* ServerSocket的 accept() 方法返回一个用于I/O的Scoket,
* 我们把这个Scoket传递给Handler的构造函数,构造一个线程实例,
* 然后启动此线程实例,它负责处理用户的请求.
**/
void runServer() {
while (true) {
try {
// 接受用户连接请求
Socket clntSock = sock.accept();
// 创建并且启动处理用户请求的线程
new Handler(this, clntSock).start();
} catch(IOException e) {
System.err.println(e);
}
}
}
/** 在指定的端口构造一个Web */
Httpd() {
super();
// 读取此Web服务器的缺省配置信息,
wsp=loadProps("httpd.properties");
// 设置Web服务器的根目录
rootDir = wsp.getProperty("rootDir", ".");
// 设置Web服务器的MIMI类型属性
mimeTypes = loadProps(wsp.getProperty("mimeProperties", "mime.properties"));
}
/** 在指定端口启动Web服务器 */
public void startServer(int portNum) {
String portNumString = null;
if (portNum == HTTP) { // 缺省端口
// 根据配置文件读取服务器端口
portNumString = wsp.getProperty("portNum");
if (portNumString != null) {
portNum = Integer.parseInt(portNumString);
}
}
try {
// 建立新的服务器端Socket,并在制定端口监听
sock = new ServerSocket(portNum);
} catch(NumberFormatException e) {
System.err.println("Httpd: \"" + portNumString +
"\" not a valid number, unable to start server");
System.exit(1);
} catch(IOException e) {
System.err.println("Network error " + e);
System.err.println("Unable to start server");
System.exit(1);
}
}
/** 读取配置信息 */
protected Properties loadProps(String fname) {
Properties sp = new Properties();
try {
// 创建要读取的配置文件的对象
FileInputStream ifile = new FileInputStream(fname);
// 读取文件
sp.load(ifile);
} catch (FileNotFoundException notFound) {
System.err.println(notFound);
System.exit(1);
} catch (IOException badLoad) {
System.err.println(badLoad);
System.exit(1);
}
return sp;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -