参考资料:
http://tomcat.apache.org/tomcat-6.0-doc/aio.html
首先引入tomcat的lib目录下的jar包:
catalina.jar,servlet-api.jar
另外要修改tomcat的server.xml,将protocal="http/1.1"什么的修改为:
<Connector port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol" connectionTimeout="20000" redirectPort="8443" />
这样就让tomcat支持推送功能了
(注意:最后关闭连接的时候,要用CometEvent的close()方法)
然后写servlet,实现comet特定接口,实现event方法:
下面的例子作用是当一个请求没有携带name参数的时候,将该请求的HttpServletResponse存放到list中,等待后面某个请求携带了name参数的时候,通过推送的方式通知所有人该消息,当然,如果时间超时,则返回error,页面再次发生请求即可。个人感觉不错的入门例子
public class MyCometServlet extends HttpServlet implements CometProcessor {
List<HttpServletResponse> responses = new ArrayList<HttpServletResponse>();
public void event(CometEvent event) throws IOException, ServletException {
HttpServletRequest request = event.getHttpServletRequest();
HttpServletResponse response = event.getHttpServletResponse();
//请求开始
if (event.getEventType() == CometEvent.EventType.BEGIN) {
//设置超时时间,单位ms
event.setTimeout(3000);
responses.add(response);
// 昵称
String name = request.getParameter("name");
System.out.println(name);
if (name == null) {
return;
}
Writer writer = null;
for(HttpServletResponse r:responses){
r.setCharacterEncoding("utf-8");
writer = r.getWriter();
writer.write("欢迎:"+name);
System.out.println("-----");
writer.flush();
event.close();
}
} else if (event.getEventType() == CometEvent.EventType.ERROR) {
//请求超时
response.setCharacterEncoding("utf-8");
response.getWriter().write("error");
response.getWriter().flush();
response.getWriter().close();
event.close();
} else if (event.getEventType() == CometEvent.EventType.END) {
//请求结束
response.setCharacterEncoding("utf-8");
response.getWriter().write("end");
response.getWriter().flush();
response.getWriter().close();
event.close();
} else if (event.getEventType() == CometEvent.EventType.READ) {
//读取请求数据
response.setCharacterEncoding("utf-8");
response.getWriter().write("read");
response.getWriter().flush();
response.getWriter().close();
event.close();
}
}
}
当然该servlet要在web.xml中配置,我的映射路径为:/cometServlet
其中页面可以通过js发送请求,也可以通过直接在地址栏输入url,都可以
例如jquery异步请求:
$.post("cometServlet",function(data){ alert(data); });
可以携带参数:
var param={"name":"dreamoftch"}; $.post("cometServlet",param,function(data){ alert(data); });
或者直接地址栏输入:
http://localhost:8080/comet_helloWorld/cometServlet?name=dreamoftch
(携带参数的话,直接就有相应,没有参数则会等待)
比较明显的例子是多个页面发多个请求,前面的几个请求不携带name参数,最后一个携带name参数,就会使前面的所有的请求都接收到响应,当然超时的话会进到error里面。
好了,晚上的收获就这些了,睡觉