代码主要由两个类构成:
服务类,默认开启一个8089的http服务
package com.twins.server;
import java.io.IOException;
import java.net.ServerSocket;
public class HttpServer {
public static void main(String[] args) throws NumberFormatException, IOException {
ServerSocket ss = new ServerSocket((args.length == 0) ? 8089 : Integer.parseInt(args[0]));
System.out.println("Service started");
while(true) {
new HttpThread(ss.accept()).start();
//ss.close();
}
}
}
2.Http线程类,封装每个Http请求的处理操作
package com.twins.server;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.StringTokenizer;
public class HttpThread extends Thread{
Socket socket;
HttpThread(Socket ss) {
this.socket = ss;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "gbk"));
OutputStream out = socket.getOutputStream();
String temp = null;
/** 打印客户端请求参数 */
while(!(temp = in.readLine()).equals("")) {
//按行读取,解析GET协议
if(temp.contains("GET")) {
System.out.println(temp + " @"+ socket.getLocalSocketAddress());
StringTokenizer st = new StringTokenizer(temp, " ");
if(st.countTokens()>=2 && st.nextToken().equalsIgnoreCase("get")) {
String path = st.nextToken();
String filename = null;
if(path.startsWith("/") && !path.endsWith("/")) {
filename = path.substring(1);
} else {
/** 默认输出index.html*/
filename = "index.html";
}
//解析html文本
if(new File(filename).exists()) {
InputStream file= new FileInputStream(filename);
byte[] data = new byte[file.available()];
file.read(data);
out.write(data);
} else {
out.write(filename.getBytes());
}
break;
}
}
}
out.close();
out.flush();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}