1. 程式人生 > >在線管理、即時通訊發送通知

在線管理、即時通訊發送通知

即時通訊 在線管理 同步刷新多個客戶端

①需要的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端。

在線聊天我們沒有做,但是技術應該就是這樣,只是怎麽讓聊天窗口,看著更好一些。

---------------------------------------------------------------------------------


在線管理、即時通訊發送通知