DWR长连接
web.xml
dwr-invoke class> uk.ltd.getahead.dwr.DWRServlet class>debug true classes java.lang.Object dwr-invoke /dwr/*
在Web-INF下创建dwr.xml
<?xml version="1.0" encoding="UTF-8"?>
ChatService 服务端
public class ChatService implements ApplicationContextAware {
private ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {
this.ctx = ctx;
}
/**
* function: 向服务器发送信息,服务器端监听ChatMessageEvent事件,当有事件触发就向所有客户端发送信息
* * @author hoojo
* * @createDate 2011-6-8 下午12:37:24
* * @param msg
* */
public void sendMessage(Message msg) {
//发布事件
ctx.publishEvent(new ChatMessageEvent(msg));
}
}
ChatMessageClient 客户端
public class ChatMessageClient implements ApplicationListener,
ServletConfigAware {
private ServletContext ctx;
public ServletContext getCtx() {
return ctx;
}
public void setCtx(ServletContext ctx) {
this.ctx = ctx;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
//如果事件类型是ChatMessageEvent就执行下面操作
if (event instanceof ChatMessageEvent) {
Message msg = (Message) event.getSource();
ServerContext context = ServerContextFactory.get();
//获得客户端所有chat页面script session连接数
if(ctx != null){
System.out.print("==========");
}
WebContext contex = WebContextFactory.get();
if(contex != null){
System.out.print("====>>>>>>>");
}
Collection sessions = context.getScriptSessionsByPage("/DWR/chat.jsp");
// Collection sessions = context.getScriptSessionsByPage(ctx.getContextPath() + "/chat.jsp");
for (ScriptSession session : sessions) {
ScriptBuffer sb = new ScriptBuffer();
Date time = msg.getTime();
String s = time.getYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate() + " "
+ time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
//执行setMessage方法
sb.appendScript("showMessage({msg: '")
.appendScript(msg.getMsg()).appendScript("', time: '")
.appendScript(s)
.appendScript("'})");
System.out.println(sb.toString());
//执行客户端script session方法,相当于浏览器执行JavaScript代码
//上面就会执行客户端浏览器中的showMessage方法,并且传递一个对象过去
session.addScript(sb);
}
}
}
@Override
public void setServletConfig(ServletConfig arg0) {
// TODO Auto-generated method stub
}
}