EXT(dwr) Web在线聊天系统群聊和私聊的实现

来源:互联网 发布:mac使用fontawesome 编辑:程序博客网 时间:2024/05/16 07:28

群聊:使用推送技术向所有在线用户发送消息

WebContext wctx = WebContextFactory.get();String currentPage = wctx.getCurrentPage();ScriptBuffer script = new ScriptBuffer();script.appendScript("receivePublicMessages(").appendData(list).appendScript(");");Collection Sessions = wctx.getScriptSessionsByPage(currentPage);for (Iterator<ScriptSession> it = Sessions.iterator(); it.hasNext();) {((ScriptSession) (it.next())).addScript(script);}


私聊:实现定向推送

1.在加载聊天页面时将用户信息写入ScriptSession中

页面载入是掉init(),然后在init中调用服务器的方法,内容如下

HttpSession httpSession = WebContextFactory.get().getSession();httpSession.setAttribute("scriptSession", thisSession.hashCode());if (thisSession.getAttribute("user") == null) {// 保存该用户地scriptSessionthisSession.setAttribute("user", httpSession.getAttribute("userSession"));}


2.在发送时候,遍历当前的所有ScriptSession,找到需要发送的人。

ScriptSession currSession = wctx.getScriptSession();// 获取当前会话的ScriptSessionString currentPage = wctx.getCurrentPage();ScriptBuffer script = new ScriptBuffer();script.appendScript("receivePrivateMessages(").appendData(list).appendScript(");");Collection Sessions = wctx.getScriptSessionsByPage(currentPage);// 获取引用当前页面的所有ScriptSessionfor (Iterator it = Sessions.iterator(); it.hasNext();) {ScriptSession otherSession = (ScriptSession) it.next();OnlineUserTO currUser = (OnlineUserTO) (otherSession.getAttribute("user"));if (currUser == null || currUser.getId() == null) {continue;}if (receiverId.equals(currUser.getId().toString())) {otherSession.addScript(script);}}currSession.addScript(script);


3.由于每次用户刷新浏览器,都会创建一个新的ScriptSession,所以需要及时pass掉过时的ScriptSession(虽然不做,基本功能也能实现,基于存储考虑)

欢迎转载,请注明出处!http://blog.csdn.net/wangyang2698341/article/details/8027793