之前的版本,在客户端发送一次请求,服务器返回结果后,运行即终止。
想要服务器可以处理多次请求,需要加入多线程。
加入多线程类,继承自 Runnable
import java.io.IOException;
import java.net.Socket;
import com.test.servlet.Servlet;
import com.test.util.IOCloseUtil;
public class Dispatcher implements Runnable{
private Request req;
private Response res;
private int code = 200;
private Socket client;
//构造参数初始化属性值
public Dispatcher(Socket client){
this.client = client;
try {
req = new Request(client.getInputStream());
res = new Response(client.getOutputStream());
} catch (IOException e) {
code = 500;
return;
}
}
@Override
public void run() {
//根据不同的URL,创建Servlet对象
Servlet servlet = WebApp.getServlet(req.getUrl());
if(servlet == null){
code = 404;
}else{
try {
servlet.Service(req, res);
} catch (Exception e) {
code = 500;
}
}
res.push2Client(code);
IOCloseUtil.closeAll(client);
}
}
修改Server类,加入多线程元素
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import com.test.util.IOCloseUtil;
/**
* 服务的启动与停止
* @author Administrator
*
*/
public class Server {
private ServerSocket server;
private boolean isShutdown = false;
public static void main(String[] args) {
Server ss = new Server();
ss.start(8888);
}
//开启服务
public void start(int port){
try {
this.server = new ServerSocket(port);
this.receive();
} catch (IOException e) {
isShutdown = true;
}
}
//接收请求
public void receive(){
while(!isShutdown){
try {
Socket client = server.accept();
//加入多线程
Dispatcher dis = new Dispatcher(client);
new Thread(dis).start();
} catch (IOException e) {
shutdown();
}
}
}
public void shutdown(){
isShutdown = true;
IOCloseUtil.closeAll(server);
}
}