websocket的sendObject方法实例
只要做的是通过webSocket的sendObject对Map<List<Object>>进行数据推送。根据业务需求 初始化加载数据后做定时器执行推送方法发送最新数据给所有人进行数据推送,而发送对象数据还需要自己写一个编码器。
maven jar包导入
<dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>sqljdbc4</artifactId> <version>4.0</version> </dependency> 下载jar包之后可以通过下面的maven命令将jar包安装到自己的私服上。 mvn install:install-file -Dfile=sqljdbc4.jar -Dpackaging=jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0
参考:http://outofmemory.cn/code-snippet/10750/sqljdbc-add-to-maven
开始
1:webSocket数据处理类
package com.woyi.first.servlet; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.woyi.api.activity.domain.Activitycard; import com.woyi.api.activity.service.IActivitycardService; import com.woyi.first.aui.controller.datareveal.ActivitycardEncoder; import com.woyi.first.util.SpringContextUtil; /** * 功能说明:websocket处理类, 使用J2EE7的标准 切忌直接在该连接处理类中加入业务处理代码 作者:liuxing(2014-11-14 * 04:20) */ // relationId和userCode是我的业务标识参数,websocket.ws是连接的路径,可以自行定义 @ServerEndpoint(value = "/websocket.ws/{userCode}", encoders = { ActivitycardEncoder.class }) public class WebsocketEndPoint { // private IZbomCrudService zbomCrudService; private static Log log = LogFactory.getLog(WebsocketEndPoint.class); @OnOpen public void onOpen(@PathParam("userCode") String userCode, Session session) { log.info("Websocket Start Connecting:" + SessionUtils.getKey(userCode)); SessionUtils.put(userCode, session); Map<String,List<Activitycard>> resultMap = new HashMap<String,List<Activitycard>>(); try { IActivitycardService activitycardService = (IActivitycardService)SpringContextUtil.getBean("activitycardService"); // 订单数、订单排名榜数、 List<Activitycard> orderList = activitycardService.findDataByOrder(); resultMap.put("orderList", orderList); // 收款额、收款排行榜 List<Activitycard> moneyList = activitycardService.findDataByMoney(); resultMap.put("moneyList", moneyList); session.getBasicRemote().sendObject(resultMap); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 收到客户端消息时触发 * * @param relationId * @param userCode * @param message * @return */ @OnMessage public void onMessage(@PathParam("userCode") String userCode, String message, Session session, HttpServletRequest request) throws IOException, Exception { } /** * 异常时触发 * @param relationId * @param userCode * @param session */ @OnError public void onError(@PathParam("userCode") String userCode, Throwable throwable, Session session) { log.info("Websocket Connection Exception:" + SessionUtils.getKey(userCode)); log.info(throwable.getMessage(), throwable); SessionUtils.remove(userCode); } /** * 关闭连接时触发 * * @param relationId * @param userCode * @param session */ @OnClose public void onClose(@PathParam("userCode") String userCode, Session session) { log.info("Websocket Close Connection:" + SessionUtils.getKey(userCode)); SessionUtils.remove(userCode); } }
2:SessionUtils对javax.websocket.Session进行持久化
package com.woyi.first.servlet; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.websocket.Session; public class SessionUtils { public static Map<String, Session> clients = new ConcurrentHashMap<String, Session>(); public static void put(String userCode, Session session) { clients.put(getKey(userCode), session); } public static Session get(String userCode) { return clients.get(getKey(userCode)); } public static void remove(String userCode) { clients.remove(getKey(userCode)); } /** * 判断是否有连接 * * @param relationId * @param userCode * @return */ public static boolean hasConnection(String userCode) { return clients.containsKey(getKey(userCode)); } /** * 组装唯一识别的key * * @param relationId * @param userCode * @return */ public static String getKey(String userCode) { return userCode; } }
3:Application获取bean
package com.woyi.first.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 获取spring容器,以访问IOC容器中定义的其他bean * @author chenhaitao */ public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * 实现ApplicationContextAware接口的回调方法,设置上下文环境 * @param applicationContext */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextUtil.applicationContext = applicationContext; } /** * 获得上下文 * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 获取对象 这里重写了bean方法,起主要作用 * @param name * @return Object 一个以所给名字注册的bean的实例 * @throws BeansException */ public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } }
4:根据业务需求自定义编码器
package com.woyi.first.aui.controller.datareveal; import java.util.List; import java.util.Map; import javax.websocket.EncodeException; import javax.websocket.Encoder; import javax.websocket.EndpointConfig; import net.sf.json.JSONArray; import com.woyi.api.activity.domain.Activitycard; public class ActivitycardEncoder implements Encoder.Text<Map<String,List<Activitycard>>> { public String encode(Map<String,List<Activitycard>> activitycard) throws EncodeException { JSONArray jsonObject = JSONArray.fromObject(activitycard); System.out.println(jsonObject.toString()); return jsonObject.toString(); } public void init(EndpointConfig ec) { System.out.println("MessageEncoder - init method called"); } public void destroy() { System.out.println("MessageEncoder - destroy method called"); } }
5:demo.jsp页面
<body onLoad="startWebSocket()"> <script type="text/javascript"> var ws = null; function startWebSocket() { var userCode = $("#userCode").val(); if (‘WebSocket‘ in window) { try { ws = new WebSocket( "ws://192.168.1.18:8066/activity/websocket.ws/" + userCode); } catch (e) { alert("1"); } } else if (‘MozWebSocket‘ in window) { ws = new MozWebSocket( "ws://192.168.1.18:8066/activity/websocket.ws/" + userCode); } else { alert("not support"); } ws.onopen = function(evt) { onMessage(evt); }; ws.onmessage = function(evt) { onMessage(evt); }; function onMessage(evt) { var map = eval("(" + evt.data + ")");//解析对象 for ( var key in map) {//循环map对象 var a = map[key]; for ( var k in a) {//循环list对象 if (k == ‘skList‘ && a[k] != null) { var info = "<ul class=‘list‘>"; var activitynum = 0; for ( var o in a[k]) { info += "<li>" + a[k][o].cardnumber + " " + a[k][o].city + " " + a[k][o].cname + " <strong>" + a[k][o].ctel + "</strong> " + a[k][o].xqmc + "</li>"; activitynum++; } info += "</ul>"; document.getElementById(‘activitynum‘).innerHTML = activitynum; document.getElementById(‘activityInfo‘).innerHTML = info; } if (k == ‘moneyList‘ && a[k] != null) { var info = "<ul class=‘list‘>"; var rank = "<ul class=‘list rank_list‘>"; var moneysum = 0; for ( var o in a[k]) { info += "<li><strong>" + a[k][o].vmoney + "元</strong>" + a[k][o].city + "</li>"; if (o < 5) { rank += "<li><span><b>" + (parseInt(o) + 1) + "</b>st</span><div><strong>" + a[k][o].vmoney + "元</strong>" + a[k][o].city + "</div></li>"; } moneysum = moneysum + parseInt(a[k][o].vmoney); } rank += "</ul>"; info += "</ul>"; document.getElementById(‘moneysum‘).innerHTML = moneysum; document.getElementById(‘moneyInfo‘).innerHTML = info; document.getElementById(‘moneyRank‘).innerHTML = rank; } if (k == ‘orderList‘ && a[k] != null) { var info = "<ul class=‘list‘>"; var rank = "<ul class=‘list rank_list‘>"; var ordernum = 0; for ( var o in a[k]) { info += "<li><strong>" + a[k][o].bid + "单</strong>" + a[k][o].city + "</li>"; if (o < 5) { rank += "<li><span><b>" + (parseInt(o) + 1) + "</b>st</span><div><strong>" + a[k][o].bid + "单</strong>" + a[k][o].city + "</div></li>"; } ordernum = ordernum + parseInt(a[k][o].bid); } rank += "</ul>"; info += "</ul>"; document.getElementById(‘ordernum‘).innerHTML = ordernum; document.getElementById(‘orderRank‘).innerHTML = rank; document.getElementById(‘orderInfo‘).innerHTML = info; } } } } ws.onclose = function(evt) { alert("close!"); }; } </script>
6:定时器 给所有人推送对象数据
Map<String,List<Activitycard>> resultMap = new HashMap<String,List<Activitycard>>(); ... for (Entry<String,Session> entry : SessionUtils.clients.entrySet()) { entry.getValue().getAsyncRemote().sendObject(resultMap); }
注1:IActivitycardService activitycardService = (IActivitycardService)SpringContextUtil.getBean("activitycardService");
在WebsocketEndPoint.java中由于无法使用@Aotowired自动装配bean所以用上述方法
注2:onOpen页面访问webSocket时就调用该方法与页面的ws.onopen一致
注3:根据业务由于不需要从页面传送对象到后台执行onMessage 所以无需进行解码(需要解码的请自行解决)
注4:demo.jsp中onmessage方法通过json解析处理推送对象数据。userCode为传递过来的HttpServletRequest.getSession.getId();
参考:http://blog.csdn.net/u012889638/article/details/49422005
原文地址:http://5474584.blog.51cto.com/5464584/1826649