`
htj1231825
  • 浏览: 38508 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

基于DWR的点对点聊天实现 server---client

dwr 
阅读更多
RemoteMessageServer 客服类
package com.gw.medical.hospital.utils.dwr;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;

@RemoteProxy(name = "RemoteMessageServer")
public class RemoteMessageServer {

	/**
	 *服务端初始化
	 */
	@RemoteMethod
	public void onPageLoad() {
		getHttpSession().setAttribute("userInfo", "CustomerService1"); // 测试用,存入模拟userInfo信息
		RemoteMessageConstant.getServerList().put(getScriptSession().getId(), getScriptSession());// 存储当前客服,到在线客服列表
	}

	/**
	 * 服务端发送信息
	 * 
	 * @param message
	 */
	@RemoteMethod
	public void addMessage(final String message) {
		HttpSession httpsession = getHttpSession();// 获取session
		String clientName = httpsession.getAttribute("clientName") == null ? "" : httpsession.getAttribute("clientName").toString();// 当前客户端ID
		ScriptSession session = RemoteMessageConstant.getMapList().get(clientName);// 根据clientName获取scriptSession;
		if (session != null) {
			// 发送消息
			String serverMessage=getHttpSession().getAttribute("userInfo").toString();
			serverMessage=serverMessage+":"+message;
			sendMessage(session,"receiveMessages",serverMessage);
		}
	}

	/**
	 * 选择下一个客户端
	 * 
	 * @return boolean
	 */
	@RemoteMethod
	public String selectClient() {
		addMessage("本次会话结束!感谢您的咨询!");
		// 销毁上一位客户
		removeClient();
		ScriptSession sessionServer = getScriptSession();// 获取客服ScriptSsession
		HttpSession httpsession = getHttpSession();// 获取session
		Map<String, ScriptSession> userMap = RemoteMessageConstant.getMapList();// 用户在线MAP
		Iterator<String> iterator = userMap.keySet().iterator();
		String clientName = "";// 获取客户端列表中的,clientName;

		while (iterator.hasNext()) {
			// 判断当前用户是否有客服接入,如未接入,接入该客户
			String tempName = iterator.next();
			if (RemoteMessageConstant.getMappingList().get(tempName) == null) {
				clientName = tempName;
				break;
			}
		}
		ScriptSession session = userMap.get(clientName);// 根据clientName获取scriptSession;
		// 更改客户端的服务ID
		if (session != null) {
			// 调用页面JS
			sendMessage(session, "setServerName", httpsession.getAttribute("userInfo").toString());
			httpsession.setAttribute("clientName", clientName);// 存储当前客户ID
			RemoteMessageConstant.getMappingList().put(session.getId(), sessionServer);// 存储对应关系,到关系MAP
			return RemoteMessageConstant.getUserNamList().get(clientName);
		}

		return "";
	}

	/**
	 * 销毁当前,服务端对应的客户端信息
	 */
	public void removeClient() {
		HttpSession httpSession = getHttpSession();// 获取httpsession
		String clientName = httpSession.getAttribute("clientName") == null ? "" : httpSession.getAttribute("clientName").toString();
		RemoteMessageConstant.getMappingList().remove(clientName);// 从关系Map中,删除对应关系。
		RemoteMessageConstant.getMapList().remove(clientName);// 从用户Map中,删除该用户;
		RemoteMessageConstant.getUserNamList().remove(clientName);//从用户名列表 删除该用户名
		httpSession.removeAttribute("clientName");// 删除当前服务端的,客户ID
	}

	/**
	 * 调用页面JS
	 * @param scriptSession,jsName:JS方法名,message:发送的信息
	 */
	public void sendMessage(ScriptSession scriptSession, String jsName, String message) {
		ScriptBuffer script = new ScriptBuffer();
		script.appendCall(jsName, message);
		scriptSession.addScript(script);
	}

	/**
	 * get set
	 */

	public ScriptSession getScriptSession() {

		return WebContextFactory.get().getScriptSession();
	}

	public HttpSession getHttpSession() {

		return WebContextFactory.get().getSession();
	}

}



RemoteMessageClient  客户端

package com.gw.medical.hospital.utils.dwr;

import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;

@RemoteProxy(name = "RemoteMessageClient")
public class RemoteMessageClient {

	/**
	 * 客户端初始化
	 */
	@RemoteMethod
	public void onPageLoadClient() {
		ScriptSession scriptSession = getScriptSession();
		HttpSession httpSession = getHttpSession();
		String clientName = scriptSession.getId();// 获取seciptSessionID作为clientName
		httpSession.setAttribute("clientName", clientName);
		RemoteMessageConstant.getMapList().put(clientName, scriptSession);// 存储用户信息到在线用户列表
		RemoteMessageConstant.getUserNamList().put(clientName, "游客");
		// 服务器显示在线用户列表;
		showOnlinClient();
		DwrScriptSessionManagerUtil dssm = new DwrScriptSessionManagerUtil();
		try {
			dssm.init();
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 客户端发送信息
	 * 
	 * @param message
	 */
	@RemoteMethod
	public void addMessageClient(String message) {
		HttpSession httpSession = getHttpSession();
		String clientName = httpSession.getAttribute("clientName") == null ? "" : httpSession.getAttribute("clientName").toString();// 获取当前登录客户端ID,在用户列表中查找相应客服
		String autoMessage = message;// 发送的内容
		ScriptSession scriptSession = RemoteMessageConstant.getMappingList().get(clientName);// 从对应Map中获取,当前客户端对应的服务端ScriptSession

		if (scriptSession != null) {
			String clientMessage=RemoteMessageConstant.getUserNamList().get(clientName);
			clientMessage+=":"+autoMessage;
			sendMessage(scriptSession,"receiveMessages",clientMessage);
		}
	}

	/**
	 * 更改服务端在线用户列表
	 */
	public void showOnlinClient() {
		Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
			// 筛选scriptSession的用户,发送目标ID,是否在scriptSession中存在
			public boolean match(ScriptSession session) {
				if (RemoteMessageConstant.getServerList().get(session.getId()) != null) {
					return true;
				} else {
					return false;
				}
			}
		}, new Runnable() {
			private ScriptBuffer script = new ScriptBuffer();

			public void run() {
				// 输出内容到页面
				Iterator<String> it = RemoteMessageConstant.getMapList().keySet().iterator();
				String autoMessage = new String();
				while (it.hasNext()) {
					String key = it.next().toString();
					// 如果没有被分配客服,显示在等待列表中
					if (RemoteMessageConstant.getMappingList().get(key) == null) {

						autoMessage += RemoteMessageConstant.getUserNamList().get(key) + ";";
					}
				}
				script.appendCall("showOnlinClient", autoMessage);
				Collection<ScriptSession> sessions = Browser.getTargetSessions();
				for (ScriptSession scriptSession : sessions) {
					scriptSession.addScript(script);
				}
			}
		});
	}


	/**
	 * get set
	 */
	/**
	 * 调用页面JS
	 * 
	 * @param scriptSession
	 *            ,jsName:JS方法名,message:发送的信息
	 */
	public void sendMessage(ScriptSession scriptSession, String jsName, String message) {
		ScriptBuffer script = new ScriptBuffer();
		script.appendCall(jsName, message);
		scriptSession.addScript(script);
	}

	public ScriptSession getScriptSession() {

		return WebContextFactory.get().getScriptSession();
	}

	public HttpSession getHttpSession() {

		return WebContextFactory.get().getSession();
	}
}




DwrScriptSessionManagerUtil 监听

package com.gw.medical.hospital.utils.dwr;

import javax.servlet.ServletException;

import org.directwebremoting.Container;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
import org.directwebremoting.extend.ScriptSessionManager;
import org.directwebremoting.servlet.DwrServlet;

public class DwrScriptSessionManagerUtil extends DwrServlet {

	private static final long serialVersionUID = -7504612622407420071L;

	public void init() throws ServletException {
		Container container = ServerContextFactory.get().getContainer();
		ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);
		ScriptSessionListener listener = new ScriptSessionListener() {
			public void sessionCreated(ScriptSessionEvent ev) {

			}

			public void sessionDestroyed(ScriptSessionEvent ev) {
				if (RemoteMessageConstant.getMappingList().get(ev.getSession().getId()) != null) {
					ScriptSession scriptSession = RemoteMessageConstant.getMappingList().get(ev.getSession().getId());
					sendMessage(scriptSession,"receiveMessages","客户端已关闭!");
				}
				// 删除该用户的列表信息
				RemoteMessageConstant.getMapList().remove(ev.getSession().getId());
				RemoteMessageConstant.getMappingList().remove(ev.getSession().getId());
				RemoteMessageConstant.getServerList().remove(ev.getSession().getId());
				RemoteMessageConstant.getUserNamList().remove(ev.getSession().getId());
				// 更新服务端在线列表
				RemoteMessageClient rc = new RemoteMessageClient();
				rc.showOnlinClient();
			}
		};
		manager.addScriptSessionListener(listener);
	}
	/**
	 * 调用页面JS
	 * @param scriptSession,jsName:JS方法名,message:发送的信息
	 */
	public void sendMessage(ScriptSession scriptSession, String jsName, String message) {
		ScriptBuffer script = new ScriptBuffer();
		script.appendCall(jsName, message);
		scriptSession.addScript(script);
	}
}



RemoteMessageConstant 静态常量

package com.gw.medical.hospital.utils.dwr;

import java.util.HashMap;
import java.util.Map;

import org.directwebremoting.ScriptSession;

public class RemoteMessageConstant {
	private static Map<String, ScriptSession> mapList = new HashMap<String, ScriptSession>();// 在线用户,Key为在线用户,Value为对应的客服,如果为空表示当前无客服接入;用户等待列表
	private static Map<String, String> userNamList = new HashMap<String, String>();// 在线用户名称
	private static Map<String, ScriptSession> mappingList = new HashMap<String, ScriptSession>();// 对应关系Map
	private static Map<String, ScriptSession> serverList = new HashMap<String, ScriptSession>();// 服务端在线列表

	/**
	 * get set
	 */
	public static Map<String, ScriptSession> getMapList() {
		return mapList;
	}

	public static void setMapList(Map<String, ScriptSession> mapList) {
		RemoteMessageConstant.mapList = mapList;
	}

	public static Map<String, ScriptSession> getMappingList() {
		return mappingList;
	}

	public static void setMappingList(Map<String, ScriptSession> mappingList) {
		RemoteMessageConstant.mappingList = mappingList;
	}

	public static Map<String, ScriptSession> getServerList() {
		return serverList;
	}

	public static void setServerList(Map<String, ScriptSession> serverList) {
		RemoteMessageConstant.serverList = serverList;
	}

	public static Map<String, String> getUserNamList() {
		return userNamList;
	}

	public static void setUserNamList(Map<String, String> userNamList) {
		RemoteMessageConstant.userNamList = userNamList;
	}


}



serverMessage.jsp  客服页
<%@ page language="java" contentType="text/html; charset=utf-8"  pageEncoding="utf-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Server</title>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/themes/default/easyui.css">
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"> </script>
<script type='text/javascript' src='<%=request.getContextPath()%>/dwr/util.js'></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/RemoteMessageServer.js"> </script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.8.3.min.js"> </script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.easyui.min.js"> </script>
<script type="text/javascript">
	$(function(){
		dwr.engine.setActiveReverseAjax(true);
		dwr.engine.setNotifyServerOnPageUnload(true);
		onPageLoad();
		//对话框初始化
		$("#messageDialog").dialog({
			title:'对话框',
			width:600,
			height:550,
			closed:false,
			cache:false
		});
	});
	  function sendMessage(message) {
		    // 通过代理调用后台的addMessage方法发送消息
		    RemoteMessageServer.addMessage(message);
	}
	// 前台接受消息的方法,由后台调用 
	  function receiveMessages(messages) {
			var p=$("
");
		   	$(p).append(messages);
		    $("#messageContent").append(p);
	  }
	  
	  //读取name值作为推送的唯一标示
	  function onPageLoad(){
	    // 通过代理,传入区别本页面的唯一标识符
	    RemoteMessageServer.onPageLoad();
	   }
	   function selectClient(){
		   RemoteMessageServer.selectClient({
			   callback:function(clientName) { 
				  if(clientName=="")
					  alert("选择失败!")
				  else
					 $("#messageContent").append("客户:"+clientName+",已成功接入!"+"<br/>");
		 			 $("#messageDialog").dialog({title:'客户:'+clientName});
			   }
			   
		   });
	   }
	   function showOnlinClient(str){
		   $(".onlineUser").html(str);
	   }
	   	/**
	 * 页面JS
	 */
	 function showIcon(){
		if($("#icondiv").css("display")=="none"){
			$("#icondiv").css("display","block");
		}else{
			$("#icondiv").css("display","none");
		}
	 }
	 function addIcon(str){
		 var img=$('<img src="<%=request.getContextPath()%>/images/dwr/'+str+'.gif"/>');
		 $("#messageTextArea").append($(img));
	 }
	 function jsSendMessage(){
		 var message=$("#messageTextArea").html();
	 	 $("#messageContent").append("我:"+message+"<br/>");
		 $("#messageTextArea").html("");
		 this.sendMessage(message);
	 }
		
</script>
<style type="text/css">
	#icondiv ul{
		width: 400px; 
		height: 130px;
		overflow: auto;
		border: 1px solid black;
	}
	#icondiv ul li{
		float: left;
		width: 45px;
		list-style: none;
		
	}
	#icondiv ul li img{
		width: 40px;
		height: 40px;
	}
</style>
</head>
<body>
	[align=center;]
			[url=javascript:void(0)]发送[/url]
			[/align]
		</div>
	</div>
	<div><input type="button" onclick="selectClient()" value="selectClient"/></div>
	[align=center;]
			[url=javascript:void(0)]发送[/url]
			[/align]
		</div>
	</div>
</body>
</html>
0
3
分享到:
评论
1 楼 fengzhaoyang 2015-04-29  
serverMessage.jsp 代码不全吧
客户端的jsp页面也没有

相关推荐

Global site tag (gtag.js) - Google Analytics