马上就要开始转到新的项目组,做一个全新的项目了,对于HTTP协议需要一定的了解,所以周末自己用Java写了一个简单的web服务器试试,只能实现简单的html文件浏览。
主要包括三个类:WebServer(监听浏览器请求),SocketThread(处理浏览器请求的进程),StringUtil(实现一些公共的操作),下面是三个类的代码.
----WebServer----
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer {
public static void main(String[] argv) throws IOException {
ServerSocket servSocket = new ServerSocket(StringUtil.LISTENING_PORT);
try {
while (true) {
Socket socket = servSocket.accept();
new SocketThread(socket).start();
}
} finally {
servSocket.close();
}
}
}
---SocketThread------
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Writer;
import java.net.Socket;
public class SocketThread extends Thread {
private Socket socket = null;
public SocketThread(Socket s) {
this.socket = s;
}
public void run() {
try {
if (socket == null) {
throw new Exception("==>SOCKET为空<==");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String fileName = "";
while (true) {
String str = reader.readLine();
if (str == null || str.length() <= 0) {
break;
}
//System.out.println("===>"+str);
if (StringUtil.isGetRequestInfo(str)) {
fileName = StringUtil.getFileName(str);
break;
}
}
//System.out.println("===>客户机IP==>"+socket.getInetAddress().toString());
//System.out.println("===>客户机端口==>"+socket.getPort());
/*
BufferedWriter writer = new BufferedWriter(new
OutputStreamWriter(socket.getOutputStream()));
*/
PrintStream outputStream = new PrintStream(socket.getOutputStream());
File file = new File(StringUtil.WEBPATH + fileName);
if (file.exists()) { //如果文件存在
StringUtil.sendHttpHead(outputStream, file);
StringUtil.sendFile(outputStream, file);
outputStream.flush();
} else { //文件没找到,返回404页面
StringUtil.send404Page(outputStream);
outputStream.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (Exception e) {
}
}
}
}
---StringUtil-----
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
/**
* @author xiaoliang
*/
public class StringUtil {
// 服务器监听的端口
public static final int LISTENING_PORT = 8080;
// 服务器文件的位置
public static final String WEBPATH = "E:";
/**
* 判断该字符串是不是浏览器发送过来的请求头信息
* @param str
* @return
*/
public static boolean isGetRequestInfo(String str) {
if (str == null || str.length() <= 0)
return false;
boolean isGetStr = true;
if (str.indexOf("GET") != 0) {
isGetStr = false;
}
if (str.indexOf("HTTP/") <= 0) {
isGetStr = false;
}
return isGetStr;
}
/**
* 获得请求信息中的文件名,默认为index.html
*
* @param str
* @return
*/
public static String getFileName(String str) {
String fileName = "index.html", s;
int httpIndex = str.lastIndexOf("HTTP/");
s = str.substring(3, httpIndex);
s = s.trim();
if (s != null && s.length() > 0 && s.indexOf(".") > 0) {
fileName = s;
}
return fileName;
}
/**
* 发送文件到客户端
*
* @param out
* @param file
*/
public static void sendFile(PrintStream out, File file) {
try {
DataInputStream in = new DataInputStream(new FileInputStream(file));
int length = (int) file.length();
byte[] buffer = new byte[length];
in.readFully(buffer);
out.write(buffer, 0, length);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送返回的头部信息
* @param out
*/
public static void sendHttpHead(PrintStream outputStream, File file) {
try {
outputStream.println("HTTP/1.0200OK");
outputStream.println("Content_Type:text/htm1");
outputStream.println("Content_Length:" + file.length());
outputStream.println("Server:moon webserver 1.0");
outputStream.println("");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 返回404页面
* @param out
*/
public static void send404Page(PrintStream out) {
try {
out.println("HTTP /1.0 404 no found");
out.println("Content_type:text/html");
out.println("");
out.println("Error404:file not found!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] argv) {
String str = "GET /11.html HTTP/1.1";
str = StringUtil.getFileName(str);
System.out.println("==>" + str + "<==");
File file = new File(StringUtil.WEBPATH + str);
if (file.exists()) {
System.out.println("exists");
} else {
System.out.println("not exists");
}
}
}