在线管理即时通讯发送通知
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在线管理即时通讯发送通知相关的知识,希望对你有一定的参考价值。
①需要的jar包java_websocket.jar
②在线聊天服务池类(在线用户管理)
package com.kentra.plugin.websocketOnline; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.java_websocket.WebSocket; /** * 在线聊天服务池类(在线用户管理) * @author KENTRASOFT * QQ 313596790 * 2015-5-25 */ public class OnlineChatServerPool { private static final Map<WebSocket,String> userconnections = new HashMap<WebSocket,String>(); private static WebSocket fhadmin = null;; /** * 获取用户名 * @param session */ public static String getUserByKey(WebSocket conn){ return userconnections.get(conn); } /** * 获取在线总数 * @param */ public static int getUserCount(){ return userconnections.size(); } /** * 获取WebSocket * @param user */ public static WebSocket getWebSocketByUser(String user){ Set<WebSocket> keySet = userconnections.keySet(); synchronized (keySet) { for (WebSocket conn : keySet) { String cuser = userconnections.get(conn); if(cuser.equals(user)){ return conn; } } } return null; } /** * 向连接池中添加连接 * @param inbound */ public static void addUser(String user, WebSocket conn){ userconnections.put(conn,user); //添加连接 } /** * 获取所有的在线用户 * @return */ public static Collection<String> getOnlineUser(){ List<String> setUsers = new ArrayList<String>(); Collection<String> setUser = userconnections.values(); for(String u:setUser){ setUsers.add(u); } return setUsers; } /** * 移除连接池中的连接 * @param inbound */ public static boolean removeUser(WebSocket conn){ if(userconnections.containsKey(conn)){ userconnections.remove(conn); //移除连接 return true; }else{ return false; } } /** * 向特定的用户发送数据 * @param user * @param message */ public static void sendMessageToUser(WebSocket conn,String message){ if(null != conn){ conn.send(message); } } /** * 向所有的用户发送消息 * @param message */ public static void sendMessage(String message){ Set<WebSocket> keySet = userconnections.keySet(); synchronized (keySet) { for (WebSocket conn : keySet) { String user = userconnections.get(conn); if(user != null){ conn.send(message); } } } } public static WebSocket getFhadmin() { return fhadmin; } public static void setFhadmin(WebSocket fhadmin) { System.err.println("---------------------fhadmin:"+fhadmin.getLocalSocketAddress().toString()); OnlineChatServerPool.fhadmin = fhadmin; } }
③在线管理类OnlineChatServer
package com.kentra.plugin.websocketOnline; import java.net.InetSocketAddress; import java.net.UnknownHostException; import net.sf.json.JSONObject; import org.java_websocket.WebSocket; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; /** * 在线管理 * @author KENTRASOFT * QQ 313596790 * 2015-5-25 */ public class OnlineChatServer extends WebSocketServer{ public OnlineChatServer(int port) throws UnknownHostException { super(new InetSocketAddress(port)); } public OnlineChatServer(InetSocketAddress address) { super(address); } /** * 触发连接事件 */ @Override public void onOpen( WebSocket conn, ClientHandshake handshake ) { } /** * 触发关闭事件 */ @Override public void onClose( WebSocket conn, int code, String reason, boolean remote ) { userLeave(conn); } /** * 客户端发送消息到服务器时触发事件 */ @Override public void onMessage(WebSocket conn, String message){ message = message.toString(); if(null != message && message.startsWith("[join]")){ this.userjoin(message.replaceFirst("\\[join\\]", ""),conn); }else if(null != message && message.startsWith("[goOut]")){ this.goOut(message.replaceFirst("\\[goOut\\]", "")); }else if(null != message && message.startsWith("[fhsms]")){ senFhsms(message.replaceFirst("\\[fhsms\\]", "")); }else if(null != message && message.startsWith("[leave]")){ this.userLeave(conn); }else if(null != message && message.startsWith("[count]")){ this.getUserCount(conn); }else if(null != message && message.startsWith("[KENTRASOFT]")){ OnlineChatServerPool.setFhadmin(conn); this.getUserList(); }else{ OnlineChatServerPool.sendMessageToUser(conn, message);//同时向本人发送消息 } } public void onFragment( WebSocket conn, Framedata fragment ) { } /** * 触发异常事件 */ @Override public void onError( WebSocket conn, Exception ex ) { if( conn != null ) { } } /** * 用户加入处理 * @param user */ public void userjoin(String user, WebSocket conn){ onlineMaganger(1,user,conn); } /** * 通知 * @param user */ public static void senFhsms(String user){ JSONObject result = new JSONObject(); result.element("type", "senFhsms"); OnlineChatServerPool.sendMessageToUser(OnlineChatServerPool.getWebSocketByUser(user),result.toString()); } /*待办消息发送*/ public static void sendNews(String layout,String content,String user){ JSONObject result = new JSONObject(); result.element("type", "senFhsms"); result.element("content", content); result.element("layout", layout); OnlineChatServerPool.sendMessageToUser(OnlineChatServerPool.getWebSocketByUser(user),result.toString()); } /** * 强制某用户下线 * @param user */ public void goOut(String user){ this.goOut(OnlineChatServerPool.getWebSocketByUser(user),"thegoout"); } /** * 强制用户下线 * @param conn */ public void goOut(WebSocket conn,String type){ JSONObject result = new JSONObject(); result.element("type", type); result.element("msg", "goOut"); OnlineChatServerPool.sendMessageToUser(conn,result.toString()); } /** * 用户下线处理 * @param user */ public void userLeave(WebSocket conn){ onlineMaganger(2,null,conn); } /** * 获取在线总数 * @param user */ public void getUserCount(WebSocket conn){ JSONObject result = new JSONObject(); result.element("type", "count"); result.element("msg", OnlineChatServerPool.getUserCount()); OnlineChatServerPool.sendMessageToUser(conn,result.toString()); } /** * 获取在线用户列表 * @param user */ public void getUserList(){ WebSocket conn = OnlineChatServerPool.getFhadmin(); if(null == conn){return;} JSONObject result = new JSONObject(); result.element("type", "userlist"); result.element("list", OnlineChatServerPool.getOnlineUser()); OnlineChatServerPool.sendMessageToUser(conn,result.toString()); } /**用户上下线管理 * @param type 1:上线;2:下线 * @param user * @param conn */ public synchronized void onlineMaganger(int type,String user, WebSocket conn){ if(type == 1){ if(null != OnlineChatServerPool.getWebSocketByUser(user)){ //判断用户是否在其它终端登录 this.goOut(OnlineChatServerPool.getWebSocketByUser(user),"thegoout"); } // else{ // goOut(conn,"goOut"); // } OnlineChatServerPool.addUser(user,conn); //向连接池添加当前的连接对象 addUserToFhadmin(user); }else{ OnlineChatServerPool.removeUser(conn); //在连接池中移除连接 this.getUserList(); } } /** * 有用户登录系统,加入在线列表 * @param conn */ public void addUserToFhadmin(String user){ WebSocket conn = OnlineChatServerPool.getFhadmin(); if(null == conn){return;} JSONObject result = new JSONObject(); result.element("type", "addUser"); result.element("user", user); OnlineChatServerPool.sendMessageToUser(conn,result.toString()); } }
head.js(main.jsp中引入了head.js)
var locat = (window.location+'').split('/'); //console.log("2行:"+window.location) //http://localhost:8081/sirdifoa/index $(function(){if('main'== locat[3]){locat = locat[0]+'//'+locat[2];}else{locat = locat[0]+'//'+locat[2]+'/'+locat[3];};}); var id; //用户ID var user = "FH"; //用于即时通讯( 当前登录用户) var TFHsmsSound = '1'; //站内信提示音效 var websocket; //websocket对象 var wimadress=""; //即时聊天服务器IP和端口 var oladress=""; //在线管理和站内信服务器IP和端口 //初始页面最顶部信息 $(function(){ getHeadMsg(); }); //初始页面信息 function getHeadMsg(){ $.ajax({ type: "POST", url: locat+'/head/getList.do?tm='+new Date().getTime(), data: encodeURI(""), dataType:'json', cache: false, success: function(data){ $("#login_user").html('<i class="ace-icon fa fa-cog"></i><span class="head_user"></span>'+data.user.userName+',您好!');//登陆者资料 user = data.user.userName; id= data.user.id; //用户ID TFHsmsSound = data.FHsmsSound; //站内信提示音效 wimadress = data.wimadress; //即时聊天服务器IP和端口 oladress = data.oladress; //在线管理和站内信服务器IP和端口 online(); //连接在线 } }); } //加入在线列表 function online(){ if (window.WebSocket) { // console.log(window.WebSocket) websocket = new WebSocket(encodeURI('ws://'+oladress)); //oladress在main.jsp页面定义 websocket.onopen = function() { //连接成功(端口连接成功,表示可以传输数据了) websocket.send('[join]'+user); // alert("你好,"+user) }; websocket.onerror = function() { //连接失败 }; websocket.onclose = function() { //连接断开 console.log("连接断开") }; //消息接收 websocket.onmessage = function(message) { var message = JSON.parse(message.data); if(message.type == 'goOut'){ $("body").html(""); goOut("1"); }else if(message.type == 'thegoout'){ $("body").html(""); goOut("2"); }else if(message.type == 'senFhsms'){ // alert(message.layout+":"+message.content); if(message.layout=="mailLayout"){ $("#"+message.layout).html("<span style='color: red;'>邮件("+message.content+")</span>"); /*顶部*/ $("#mailLayout_top").html("<span class='scorool_top'>邮件(<span class='scorool_top'>"+message.content+"</span>)</span>"); } if(message.layout=="test"){ alert("弹窗通知:"+message.content) } if("flowTodo" == message.layout){//待办 if(message.content){ // navTab.closeCurrentTab("flowAuth"+message.content);//手机上处理了,关闭PC页面 //alert(message.content); //弹出通知提示.... } //刷新首页我的待办 $("#todoListId").loadUrl("portalmanage/getTodoList.do","",function(){ $('#todoListId').parent().find("[layoutH]").layoutH(); }); //刷新待办列表 navTab.reloadFlag("todolist"); //刷新首页已办 $("#haveTodoList").loadUrl("portalmanage/getHasTodoList.do","",function(){ $('#haveTodoList').parent().find("[layoutH]").layoutH(); }); //刷新我的已办列表 navTab.reloadFlag("haveTodoList"); } if("informNum" == message.layout){//通知 if(message.content > '0'){//通知数量 /*底部*/ $("#inform_count_a").html("<span style='color: red;'>通知("+message.content+")</span>"); $("#inform_count_a").attr("href",'inform/index.do?pKey=1&key=546&informType=1'); $("#inform_count_a").attr("rel",'inform'); /*顶部*/ $("#inform_count_a_top").html("<span class='scorool_top'>、通知(<span class='scorool_top'>"+message.content+"</span>)</span>"); $("#inform_count_a_top").attr("href",'inform/index.do?pKey=1&key=546&informType=1'); $("#inform_count_a_top").attr("rel",'inform'); }else{ $("#inform_count_a").html(""); $("#inform_count_a_top").html(""); } } if("informFileNum" == message.layout){//文件传阅 if(message.content > '0'){//文件传阅数量 /*底部*/ $("#informFile_count_a").html("<span style='color: red;'>传阅("+message.content+")</span>"); $("#informFile_count_a").attr("href",'inform/index.do?pKey=1&key=751&informType=2'); $("#informFile_count_a").attr("rel",'inform'); /*顶部*/ $("#informFile_count_a_top").html("<span class='scorool_top'>、传阅(<span class='scorool_top'>"+message.content+"</span>)</span>"); $("#informFile_count_a_top").attr("href",'inform/index.do?pKey=1&key=751&informType=2'); $("#informFile_count_a_top").attr("rel",'inform'); }else{ $("#informFile_count_a").html(""); $("#informFile_count_a_top").html(""); } } } }; } } //下线 function goOut(msg){ window.location.href=locat+"/logout.do?msg="+msg; } //去通知收信人有站内信接收 function fhsmsmsg(USERNAME){ var arrUSERNAME = USERNAME.split(';'); for(var i=0;i<arrUSERNAME.length;i++){ websocket.send('[fhsms]'+arrUSERNAME[i]);//发送通知 } } //读取站内信时减少未读总数 function readFhsms(){ mailCount = Number(mailCount)-1; $("#mailCount").html(Number(mailCount) <= 0 ?'0':mailCount); } //修改个人资料 function editUserH(){ jzts(); var diag = new top.Dialog(); diag.Drag=true; diag.Title ="个人资料"; diag.URL = locat+'/user/goEditU.do?id='+id+'&fx=head'; diag.Width = 469; diag.Height = 469; diag.CancelEvent = function(){ //关闭事件 diag.close(); }; diag.show(); }
在线管理界面jsp
onlinemanager_list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <head> <title>在线管理</title> <base href="<%=basePath%>"> </head> <body> <div class="pageHeader"> <form onsubmit="return navTabSearch(this);" action="onlinemanager/list.do" method="post"> </form> </div> <div class="pageContent layoutBox" > <table style="margin-top:10px;"> <tr bgcolor="#E0E0E0" style="height:26px;"> <td style="padding-left: 15px;">在线人数:</td> <td> <div style="width:39px;" id="onlineCount">0</div> </td> </tr> </table> <table class="table" width="100%" > <thead id="online-table"> <tr> <th class="center" style="width: 50px;"> <div class="gridCol" title=""><input type="checkbox" group="names" class="checkboxCtrl"></div> </th> <th class='center' style="width:65px;">序号</th> <th>用户名</th> <th class="center" style="width: 120px;">操作</th> </tr> </thead> <tbody id="userlist"> </tbody> </table> <div> <a class="button" title="批量强制下线" href="javascript:;" onclick="makeAll()" ><span>批量强制下线</span></a> </div> </div> <script type="text/javascript"> //初始化 $(function(){ online(); }); var websocketonline;//websocke对象 var userCount = 0; //在线总数 function online(){ if (window.WebSocket) { websocketonline = new WebSocket(encodeURI('ws://'+top.oladress)); //oladress在main.jsp页面定义 websocketonline.onopen = function() { websocketonline.send('[KENTRASOFT]fhadmin');//连接成功 }; websocketonline.onerror = function() { //连接失败 }; websocketonline.onclose = function() { //连接断开 }; //消息接收 websocketonline.onmessage = function(message) { var message = JSON.parse(message.data); console.log(message.list); if (message.type == 'count') { userCount = message.msg; }else if(message.type == 'userlist'){ $("#userlist").html(''); $.each(message.list, function(i, user){ $("#userlist").append( '<tr target="sname_user" rel="'+user+'">'+ '<td class="center" style="width: 47px;">'+ ("admin"==user?" ":'<div><input name="names" value="'+user+'" type="checkbox"></div>')+ '</td>'+ '<td class="center" style="width: 61px;">'+(i+1)+'</td>'+ '<td>'+user+'</td>'+ '<td style="width: 113px;" >'+ ("admin"==user?" ":'<a class="button" href="javascript:;" onclick="goOutTUser(\''+user+'\')"><span>强制下线</span></a>')+ '</td>'+ '</tr>' ); userCount = i+1; }); $("#onlineCount").html(userCount); }else if(message.type == 'addUser'){ $("#userlist").append( '<tr target="sname_user" rel="'+message.user+'">'+ '<td class="center" style="width: 47px;">'+ ("admin"==user?" ":'<div><input name="names" value="'+user+'" type="checkbox"></div>')+ '</td>'+ '<td class="center" style="width: 61px;">'+(userCount+1)+'</td>'+ '<td>'+message.user+'</td>'+ '<td class="center" style="width: 113px;" >'+ ("admin"==message.user?" ":'<a class="button" href="javascript:;" onclick="goOutTUser(\''+message.user+'\')"><span>强制下线</span></a>')+ '</td>'+ '</tr>' ); userCount = userCount+1; $("#onlineCount").html(userCount); } }; } } //强制某用户下线 function goOutUser(theuser){ websocketonline.send('[goOut]'+theuser); } //强制某用户下线 function goOutTUser(theuser) { if ('admin' == theuser) { alertMsg.info('不能强制下线admin用户!') return; } alertMsg.confirm("确定要强制[" + theuser + "]下线吗?", { okCall : function() { goOutUser(theuser); } }); } //批量操作 function makeAll(){ var nameStr = ""; navTab.getCurrentPanel().find("input:checked").filter( "[name=names]").each(function(i) { var val = $(this).val(); if ("admin" != val) { nameStr += val + " "; } }); if (!nameStr) { alertMsg.info('请选择用户'); return; } alertMsg.confirm("确定要强制[" + nameStr + "]下线吗?", { okCall : function() { navTab.getCurrentPanel().find("input:checked").filter( "[name=names]").each(function(i) { var val = $(this).val(); if ("admin" != val) { goOutUser(val); } }); } }); } </script> </body> </html>
说明:
服务端调用,客户端监听
OnlineChatServer.sendNews("flowTodo","流程提交", user.getUserName());//服务器调用 //客户端监听 websocket.onmessage = function(message) { var message = JSON.parse(message.data); if(message.type == 'goOut'){ $("body").html(""); goOut("1"); }else if(message.type == 'thegoout'){ $("body").html(""); goOut("2"); }else if(message.type == 'senFhsms'){ alert(message.layout+":"+message.content); }
客户端调用,服务端监听
//客户端 连接成功(端口连接成功,表示可以传输数据了) websocket.send('[join]'+user); /** * 客户端发送消息到服务器时触发事件 */ @Override public void onMessage(WebSocket conn, String message){ message = message.toString(); if(null != message && message.startsWith("[join]")){ this.userjoin(message.replaceFirst("\\[join\\]", ""),conn); }else if(null != message && message.startsWith("[goOut]")){ this.goOut(message.replaceFirst("\\[goOut\\]", "")); }else if(null != message && message.startsWith("[fhsms]")){ senFhsms(message.replaceFirst("\\[fhsms\\]", "")); }else if(null != message && message.startsWith("[leave]")){ this.userLeave(conn); }else if(null != message && message.startsWith("[count]")){ this.getUserCount(conn); }else if(null != message && message.startsWith("[KENTRASOFT]")){ OnlineChatServerPool.setFhadmin(conn); this.getUserList(); }else{ OnlineChatServerPool.sendMessageToUser(conn, message);//同时向本人发送消息 } }
其他:即时通讯,在线聊天的两个类
ChatServer.java
package com.kentra.plugin.websocketInstantMsg; import java.io.IOException; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Date; import net.sf.json.JSONObject; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; /** * 即时通讯 * @author KENTRASOFT * QQ 313596790 * 2015-5-16 */ public class ChatServer extends WebSocketServer{ public ChatServer(int port) throws UnknownHostException { super(new InetSocketAddress(port)); } public ChatServer(InetSocketAddress address) { super(address); } /** * 触发连接事件 */ @Override public void onOpen( WebSocket conn, ClientHandshake handshake ) { //this.sendToAll( "new connection: " + handshake.getResourceDescriptor() ); //System.out.println("===" + conn.getRemoteSocketAddress().getAddress().getHostAddress()); } /** * 触发关闭事件 */ @Override public void onClose( WebSocket conn, int code, String reason, boolean remote ) { userLeave(conn); } /** * 客户端发送消息到服务器时触发事件 */ @Override public void onMessage(WebSocket conn, String message){ message = message.toString(); if(null != message && message.startsWith("FHadminKENTRASOFT")){ this.userjoin(message.replaceFirst("FHadminKENTRASOFT", ""),conn); }if(null != message && message.startsWith("LeaveFHadminKENTRASOFT")){ this.userLeave(conn); }if(null != message && message.contains("fhadmin886")){ String toUser = message.substring(message.indexOf("fhadmin886")+10, message.indexOf("fhfhadmin888")); message = message.substring(0, message.indexOf("fhadmin886")) +"[私信] "+ message.substring(message.indexOf("fhfhadmin888")+12, message.length()); ChatServerPool.sendMessageToUser(ChatServerPool.getWebSocketByUser(toUser),message);//向所某用户发送消息 ChatServerPool.sendMessageToUser(conn, message);//同时向本人发送消息 }else{ ChatServerPool.sendMessage(message.toString());//向所有在线用户发送消息 } } public void onFragment( WebSocket conn, Framedata fragment ) { } /** * 触发异常事件 */ @Override public void onError( WebSocket conn, Exception ex ) { ex.printStackTrace(); if( conn != null ) { //some errors like port binding failed may not be assignable to a specific websocket } } /** * 用户加入处理 * @param user */ public void userjoin(String user, WebSocket conn){ JSONObject result = new JSONObject(); result.element("type", "user_join"); result.element("user", "<a onclick=\"toUserMsg('"+user+"');\">"+user+"</a>"); ChatServerPool.sendMessage(result.toString()); //把当前用户加入到所有在线用户列表中 String joinMsg = "{\"from\":\"[系统]\",\"content\":\""+user+"上线了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}"; ChatServerPool.sendMessage(joinMsg); //向所有在线用户推送当前用户上线的消息 result = new JSONObject(); result.element("type", "get_online_user"); ChatServerPool.addUser(user,conn); //向连接池添加当前的连接对象 result.element("list", ChatServerPool.getOnlineUser()); ChatServerPool.sendMessageToUser(conn, result.toString()); //向当前连接发送当前在线用户的列表 } /** * 用户下线处理 * @param user */ public void userLeave(WebSocket conn){ String user = ChatServerPool.getUserByKey(conn); boolean b = ChatServerPool.removeUser(conn); //在连接池中移除连接 if(b){ JSONObject result = new JSONObject(); result.element("type", "user_leave"); result.element("user", "<a onclick=\"toUserMsg('"+user+"');\">"+user+"</a>"); ChatServerPool.sendMessage(result.toString()); //把当前用户从所有在线用户列表中删除 String joinMsg = "{\"from\":\"[系统]\",\"content\":\""+user+"下线了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}"; ChatServerPool.sendMessage(joinMsg); //向在线用户发送当前用户退出的消息 } } public static void main( String[] args ) throws InterruptedException , IOException { WebSocketImpl.DEBUG = false; int port = 8887; //端口 ChatServer s = new ChatServer(port); s.start(); //System.out.println( "服务器的端口" + s.getPort() ); } }
ChatServerPool.java
package com.kentra.plugin.websocketInstantMsg; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.java_websocket.WebSocket; /** * 即时通讯 * @author KENTRASOFT * QQ 313596790 * 2015-5-16 */ public class ChatServerPool { private static final Map<WebSocket,String> userconnections = new HashMap<WebSocket,String>(); /** * 获取用户名 * @param session */ public static String getUserByKey(WebSocket conn){ return userconnections.get(conn); } /** * 获取WebSocket * @param user */ public static WebSocket getWebSocketByUser(String user){ Set<WebSocket> keySet = userconnections.keySet(); synchronized (keySet) { for (WebSocket conn : keySet) { String cuser = userconnections.get(conn); if(cuser.equals(user)){ return conn; } } } return null; } /** * 向连接池中添加连接 * @param inbound */ public static void addUser(String user, WebSocket conn){ userconnections.put(conn,user); //添加连接 } /** * 获取所有的在线用户 * @return */ public static Collection<String> getOnlineUser(){ List<String> setUsers = new ArrayList<String>(); Collection<String> setUser = userconnections.values(); for(String u:setUser){ setUsers.add("<a onclick=\"toUserMsg('"+u+"');\">"+u+"</a>"); } return setUsers; } /** * 移除连接池中的连接 * @param inbound */ public static boolean removeUser(WebSocket conn){ if(userconnections.containsKey(conn)){ userconnections.remove(conn); //移除连接 return true; }else{ return false; } } /** * 向特定的用户发送数据 * @param user * @param message */ public static void sendMessageToUser(WebSocket conn,String message){ if(null != conn && null != userconnections.get(conn)){ conn.send(message); } } /** * 向所有的用户发送消息 * @param message */ public static void sendMessage(String message){ Set<WebSocket> keySet = userconnections.keySet(); synchronized (keySet) { for (WebSocket conn : keySet) { String user = userconnections.get(conn); if(user != null){ conn.send(message); } } } } }
---------------------------------------------------------------------------------
① OnlineChatServerPool中主要是连接池的管理(向连接池中添加对象,移除对象)
②OnlineChatServer.java 中主要是在线管理类,管理上线(上线,将上线的用户添加到连接池中,并刷新在线用户列表),
强制下线,监听下线(下线后将连接池中的对象移除,并刷新在线用户列表)。监听处理客服端发来的消息。
③main.jsp 中引入了head.js ,head.js中初始化的时候,就建立连接,连接成功后,把用户名发送到服务器。
head.js中//消息接收 websocket.onmessage ,监听着来自服务器的消息,不同的消息类型有不同的处理方式,比如待办,主要是刷新待办列表。
④这里也可以实现当有通知消息的时候,我们在右下角弹出窗口,及时通知。或者右下角提示大家某某某上线了或下线了。
及时通讯也应用于在线聊天,但是这个受制于网络条件,如果网速不好,可能有的消息无法收到。
⑥ChatServer.java主要是聊天的服务类
⑦ChatServerPool.java聊天池管理,通知某某某上线了,给对应的用户发送消息等。
总结:
其实我们更多的用的是在线管理和站内信管理。只是用了即时通讯的技术和思想。上下线管理集中体现在实时在线用户列表,可以了解哪些用户在线,这样也方便我们发布版本的时候监控
系统使用情况。
在处理流程时,运用即时通讯,刷新其他客户端的待办列表,使信息实时同步。微信端处理后,刷新PC端。
在线聊天我们没有做,但是技术应该就是这样,只是怎么让聊天窗口,看着更好一些。
---------------------------------------------------------------------------------
以上是关于在线管理即时通讯发送通知的主要内容,如果未能解决你的问题,请参考以下文章