WebServer类:服务器端监听请求:
package server;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer {
public static boolean isRun = true;
public WebServer(){
try{
ServerSocket sever = new ServerSocket(6231);
while (isRun) {
//阻塞监听
Socket socket = sever.accept();
//根据监听到的不同请求,创建不同线程,对相应请求进行处理
new DisposeSocket(socket);
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new WebServer();
}
}
package server;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class DisposeSocket extends Thread{
private Socket socket;
public DisposeSocket(Socket socket){
this.socket =socket;
this.start();
}
public void run(){
OutputStream out = null;
try{
InputStream in = this.socket.getInputStream();
out = this.socket.getOutputStream();
//将写入流封装成Response响应对象
Response response = new Response(out);
//将读取流封装成Request对象
Request request = new Request(in);
System.out.println(request);
//得到url
String url = request.getUrl();
//利用工厂类创建业务组件
Servlet servlet = ServiceFactory.getServlet(url);
if (servlet!=null) {//请求的是业务组件
//执行业务方法
servlet.service(request, response);
}else {//请求的是文件
response.sendFile(url);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
out.flush();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Request类:封装socket读取流的请求对象
package server;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
/**
* 封装socket读取流的请求对象
* @author Administrator
*
*/
public class Request {
private InputStream in;
private String url;
/**请求参数的集合*/
private Map<String, String> paramMap = new HashMap<String,String>();
public Request(InputStream in){
this.in = in;
try {
//读取客户端请求的信息
byte[] b = new byte[1024];
this.in.read(b);
//将byte数组转为string
String string = new String(b).trim();
System.out.println(string);
if (string.startsWith("GET")) {//如果是get请求
pressGet(string);
}else if(string.startsWith("POST")){//如果是post请求
pressPost(string);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void pressPost(String arg) {
//按空格截取
String[] string = arg.split("\\s+");
this.url = string[1].substring(1);
this.setMap(string[string.length-1]);
}
private void pressGet(String arg) {
//按空格截取
String[] string = arg.split("\\s+");
if (string[1].indexOf("?") != -1) {//请求业务组件
//按?拆分第一个是URL,第二个是请求数据
String[] str = string[1].split("[?]");
this.url = str[0].substring(1);
this.setMap(str[1]);
}else{//请求的是文件
this.url = string[1].substring(1);
}
}
private void setMap(String string) {
//解码:将ISO8859-1解码成中文字
try {
string = URLDecoder.decode(string,"GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] str = string.split("&");
for (String st : str) {
String[] s = st.split("=");
if (s.length == 2) {
this.paramMap.put(s[0], s[1]);
}else if(s.length == 1){
this.paramMap.put(s[0], "");
}
}
}
public String getUrl() {
return url;
}
/**
* 根据键获取值
* @param arg 键
* @return
*/
public String getParameter(String key){
return this.paramMap.get(key);
}
public String toString(){
return "url:"+this.url+" paramMap:"+this.paramMap;
}
}
Response类:向客户端发送信息的响应对象
package server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 向客户端发送信息的响应对象
* @author Administrator
*
*/
public class Response {
/**从socket中得到写入流*/
private OutputStream out;
public Response(OutputStream out){
this.out = out;
}
/**
* 向客户端发送文本消息
* @param str 消息内容
*/
public void sendMessage(String str){
try {
this.out.write(str.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 向客户端发送文件消息
* @param filePath 文件路径
*/
public void sendFile(String filePath){
File file = new File(filePath);
if (!file.exists()) {//文件不存在直接跳出
return;
}
InputStream in = null ;
try {
in = new FileInputStream(filePath);
//从文件中读取数据,写入到out中,由于out是socket中得到,输出的地点是客户端
byte[] by = new byte[1024];
int len = 0;
while((len = in.read(by))!= -1){
this.out.write(by,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if (in!=null) {
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
ServiceFactory :创建业务层组建的工厂类
package server;
import java.io.FileReader;
import java.util.Properties;
public class ServiceFactory {
private static Properties pro = new Properties();
static{
try {
pro.load(new FileReader("info.txt"));
} catch (Exception e) {
e.printStackTrace();
}
}
public ServiceFactory(){
}
public static Servlet getServlet(String url){
try {
String classUrl = pro.getProperty(url);
if (classUrl==null) {//表示客户端请求的是文件
return null;
}
Class<?> c = Class.forName(classUrl);
Object obj = c.newInstance();
return (Servlet)obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
//System.out.println(ServiceFactory.getServlet("asf"));
}
}
package server;
/**
* 所有业务组件都要实现的接口
* @author Administrator
*
*/
public interface Servlet {
/**
* 业务方法
* @param request
* @param response
*/
public void service(Request request,Response response);
}