①需要的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 Mapuserconnections = new HashMap (); 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 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 getOnlineUser(){ List setUsers = new ArrayList (); Collection 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 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(''+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("邮件("+message.content+")"); /*顶部*/ $("#mailLayout_top").html("邮件("+message.content+")"); } 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("通知("+message.content+")"); $("#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("、通知("+message.content+")"); $("#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("传阅("+message.content+")"); $("#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("、传阅("+message.content+")"); $("#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
在线管理界面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 + "/"; %>在线管理 ">