[color=red]运行此服务器程序的前提是首先在XP上安装IIS,然后在默认的服务器目录C:\Inetpub\wwwroot
下新建一个dog.html文件。之后,运行下文的程序WebServer.java,后在IE输入http://localhost/dog.html就行了。[/color]
WebServer.java
import java.io.*;
import java.net.*;
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 = 2011;
if(args.length == 1){
port = Integer.parseInt(args[0]);
}
//启动服务器
new WebServer().webStart(port);
}
}
Processor.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Processor extends Thread {
private Socket sockets;
private InputStream in;
//为方便使用PrintStream
private PrintStream out;
//限定访问的文件地址
private final static String WEB_ROOT = "C:\\Inetpub\\wwwroot
";
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();
}
}
}