[color=red]运行程序后在IE输入http://localhost/1.html就行了[/color]
public class WebServer {
private void webStart(int port){
try {
//新建一个服务器ServerSocket
ServerSocket socketServer = new ServerSocket(port);
while(true){
//等待客户端的请求
Socket socket = socketServer.accept();
new Processor(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
int port = 80;
if(args.length == 1){
port = Integer.parseInt(args[0]);
}
//启动服务器
new WebServer().webStart(port);
}
}
public class Processor extends Thread {
private Socket sockets;
private InputStream in;
//为方便使用PrintStream
private PrintStream out;
//限定访问的文件地址
private final static String WEB_ROOT = "C:\\WebRoot\\";
public Processor(Socket socket) {
this.sockets = socket;
try {
//初始化in,out
in = sockets.getInputStream();
out = new PrintStream(sockets.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String filename = parse(in);
sendFile(filename);
}
//读客户端传过来的信息,返回需要请求的文件名
public String parse(InputStream in) {
//建立一个BufferedReader读客户端传过来的信息
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String filename = null;
try {
String httpMessage = br.readLine();
String[] content = httpMessage.split(" ");
if (content.length != 3) {
sendErrorMessage(400, "客户端请求错误");
}
System.out.println("code:" + content[0] + ",name:" + content[1]
+ ",http version" + content[2]);
filename = content[1];
} catch (IOException e) {
e.printStackTrace();
}
return filename;
}
//错误处理
public void sendErrorMessage(int errorCoder, String errorMessage) {
}
//读取本地文件
public void sendFile(String filename) {
File file = new File(Processor.WEB_ROOT + filename);
if (!file.exists()) {
this.sendErrorMessage(404, "文件名不存在错误");
}
try {
//读取本地文件,并放到content里面,再用out写到客户端那边
InputStream in = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
in.read(content);
out.write(content);
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}