大学时期自己看《How Tomcat Works》这本书的的时候动手写的一个小玩意儿:服务端的socket多线程处理框架。大体结构如下:
客户端的请求首先会进入请求队列,处理器线程池会向请求队列获取请求并且分配分配处理器,每个处理器分配一个线程。处理器可以指定interceptor,处理逻辑都实现在ResponseHandler中。空闲时,处理器线程会休眠直到有新的请求到来。
使用例子:
1.配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<log-config file="d:\log.txt" level="INFO" />
<servers>
<server>
<port value="12121" />
<requestQueue size="100" />
<pool minThread="1" maxThread="10" />
<interceptors>
<interceptor class="xiaoyang.server.sample.simple.Mynterceptor1" />
<interceptor class="xiaoyang.server.sample.simple.Mynterceptor2" />
</interceptors>
<serverHandler class="xiaoyang.server.sample.simple.MyServerHandler" />
</server>
<server>
<port value="12122" />
<serverHandler class="xiaoyang.server.sample.simple.MyServerHandler" />
</server>
</servers>
</config>
2.继承抽象类ServerHandler,实现服务端处理逻辑方法"process(request)":
public class MyServerHandler extends ServerHandler {
Logger logger=ServerLoggerFactory.getLogger(MyServerHandler.class);
@Override
public void process(Request request) {
Socket requestSocket=request.getRequestSocket();
//socket已获取,实现你自己的逻辑...
}
}
3.如果需要的话,可以实现拦截器:
public class Mynterceptor1 implements Interceptor{
@Override
public void intercept(InvocationHandle handler) {
System.out.println("Mynterceptor1 before invoke()");
handler.invoke();
System.out.println("Mynterceptor1 after invoke()");
}
4.最后,启动server:
List<Server> servers=ServerFactory.createServer("config.xml");
for (Server server : servers) {
server.start();
}
或者:
Server server=ServerFactory.createServer(12121, 40, 1, 5, new MyServerHandler());
server.start();
SocketServer.jar 下载地址:http://download.csdn.net/detail/xiaoyang0611/8426297