SpringMVC整合websocket实现消息推送及触发功能
程序员文章站
2023-11-27 11:18:04
本文为大家分享了springmvc整合websocket实现消息推送,供大家参考,具体内容如下
1.创建websocket握手协议的后台
(1)handshake的实现...
本文为大家分享了springmvc整合websocket实现消息推送,供大家参考,具体内容如下
1.创建websocket握手协议的后台
(1)handshake的实现类
/** *project name: price *file name: handshake.java *package name: com.yun.websocket *date: 2016年9月3日 下午4:44:27 *copyright (c) 2016,578888218@qq.com all rights reserved. */ package com.yun.websocket; import java.util.map; import org.springframework.http.server.serverhttprequest; import org.springframework.http.server.serverhttpresponse; import org.springframework.http.server.servletserverhttprequest; import org.springframework.web.socket.websockethandler; import org.springframework.web.socket.server.handshakeinterceptor; /** *title: handshake<br/> *description: *@company: 青岛励图高科<br/> *@author: 刘云生 *@version: v1.0 *@since: jdk 1.7.0_80 *@date: 2016年9月3日 下午4:44:27 <br/> */ public class handshake implements handshakeinterceptor{ @override public boolean beforehandshake(serverhttprequest request, serverhttpresponse response, websockethandler wshandler, map<string, object> attributes) throws exception { // todo auto-generated method stub string jspcode = ((servletserverhttprequest) request).getservletrequest().getparameter("jspcode"); // 标记用户 //string userid = (string) session.getattribute("userid"); if(jspcode!=null){ attributes.put("jspcode", jspcode); }else{ return false; } return true; } @override public void afterhandshake(serverhttprequest request, serverhttpresponse response, websockethandler wshandler, exception exception) { // todo auto-generated method stub } }
(2)mywebsocketconfig的实现类
/** *project name: price *file name: mywebsocketconfig.java *package name: com.yun.websocket *date: 2016年9月3日 下午4:52:29 *copyright (c) 2016,578888218@qq.com all rights reserved. */ package com.yun.websocket; import javax.annotation.resource; import org.springframework.stereotype.component; import org.springframework.web.servlet.config.annotation.enablewebmvc; import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; import org.springframework.web.socket.config.annotation.enablewebsocket; import org.springframework.web.socket.config.annotation.websocketconfigurer; import org.springframework.web.socket.config.annotation.websockethandlerregistry; /** *title: mywebsocketconfig<br/> *description: *@company: 青岛励图高科<br/> *@author: 刘云生 *@version: v1.0 *@since: jdk 1.7.0_80 *@date: 2016年9月3日 下午4:52:29 <br/> */ @component @enablewebmvc @enablewebsocket public class mywebsocketconfig extends webmvcconfigureradapter implements websocketconfigurer{ @resource mywebsockethandler handler; @override public void registerwebsockethandlers(websockethandlerregistry registry) { // todo auto-generated method stub registry.addhandler(handler, "/wsmy").addinterceptors(new handshake()); registry.addhandler(handler, "/wsmy/sockjs").addinterceptors(new handshake()).withsockjs(); } }
(3)mywebsockethandler的实现类
/** *project name: price *file name: mywebsockethandler.java *package name: com.yun.websocket *date: 2016年9月3日 下午4:55:12 *copyright (c) 2016,578888218@qq.com all rights reserved. */ package com.yun.websocket; import java.io.ioexception; import java.util.hashmap; import java.util.iterator; import java.util.map; import java.util.map.entry; import org.springframework.stereotype.component; import org.springframework.web.socket.closestatus; import org.springframework.web.socket.textmessage; import org.springframework.web.socket.websockethandler; import org.springframework.web.socket.websocketmessage; import org.springframework.web.socket.websocketsession; import com.google.gson.gsonbuilder; /** *title: mywebsockethandler<br/> *description: *@company: 青岛励图高科<br/> *@author: 刘云生 *@version: v1.0 *@since: jdk 1.7.0_80 *@date: 2016年9月3日 下午4:55:12 <br/> */ @component public class mywebsockethandler implements websockethandler{ public static final map<string, websocketsession> usersocketsessionmap; static { usersocketsessionmap = new hashmap<string, websocketsession>(); } @override public void afterconnectionestablished(websocketsession session) throws exception { // todo auto-generated method stub string jspcode = (string) session.gethandshakeattributes().get("jspcode"); if (usersocketsessionmap.get(jspcode) == null) { usersocketsessionmap.put(jspcode, session); } for(int i=0;i<10;i++){ //broadcast(new textmessage(new gsonbuilder().create().tojson("\"number\":\""+i+"\""))); session.sendmessage(new textmessage(new gsonbuilder().create().tojson("\"number\":\""+i+"\""))); } } @override public void handlemessage(websocketsession session, websocketmessage<?> message) throws exception { // todo auto-generated method stub //message msg=new gson().fromjson(message.getpayload().tostring(),message.class); //msg.setdate(new date()); // sendmessagetouser(msg.getto(), new textmessage(new gsonbuilder().setdateformat("yyyy-mm-dd hh:mm:ss").create().tojson(msg))); session.sendmessage(message); } @override public void handletransporterror(websocketsession session, throwable exception) throws exception { // todo auto-generated method stub if (session.isopen()) { session.close(); } iterator<entry<string, websocketsession>> it = usersocketsessionmap .entryset().iterator(); // 移除socket会话 while (it.hasnext()) { entry<string, websocketsession> entry = it.next(); if (entry.getvalue().getid().equals(session.getid())) { usersocketsessionmap.remove(entry.getkey()); system.out.println("socket会话已经移除:用户id" + entry.getkey()); break; } } } @override public void afterconnectionclosed(websocketsession session, closestatus closestatus) throws exception { // todo auto-generated method stub system.out.println("websocket:" + session.getid() + "已经关闭"); iterator<entry<string, websocketsession>> it = usersocketsessionmap .entryset().iterator(); // 移除socket会话 while (it.hasnext()) { entry<string, websocketsession> entry = it.next(); if (entry.getvalue().getid().equals(session.getid())) { usersocketsessionmap.remove(entry.getkey()); system.out.println("socket会话已经移除:用户id" + entry.getkey()); break; } } } @override public boolean supportspartialmessages() { // todo auto-generated method stub return false; } /** * 群发 * @title: broadcast * @description: todo * @param: @param message * @param: @throws ioexception * @return: void * @author: 刘云生 * @date: 2016年9月10日 下午4:23:30 * @throws */ public void broadcast(final textmessage message) throws ioexception { iterator<entry<string, websocketsession>> it = usersocketsessionmap .entryset().iterator(); // 多线程群发 while (it.hasnext()) { final entry<string, websocketsession> entry = it.next(); if (entry.getvalue().isopen()) { new thread(new runnable() { public void run() { try { if (entry.getvalue().isopen()) { entry.getvalue().sendmessage(message); } } catch (ioexception e) { e.printstacktrace(); } } }).start(); } } } /** * 给所有在线用户的实时工程检测页面发送消息 * * @param message * @throws ioexception */ public void sendmessagetojsp(final textmessage message,string type) throws ioexception { iterator<entry<string, websocketsession>> it = usersocketsessionmap .entryset().iterator(); // 多线程群发 while (it.hasnext()) { final entry<string, websocketsession> entry = it.next(); if (entry.getvalue().isopen() && entry.getkey().contains(type)) { new thread(new runnable() { public void run() { try { if (entry.getvalue().isopen()) { entry.getvalue().sendmessage(message); } } catch (ioexception e) { e.printstacktrace(); } } }).start(); } } } }
2.创建websocket握手处理的前台
<script> var path = '<%=basepath%>'; var userid = 'lys'; if(userid==-1){ window.location.href="<%=basepath2%>" rel="external nofollow" ; } var jspcode = userid+"_aaa"; var websocket; if ('websocket' in window) { websocket = new websocket("ws://" + path + "wsmy?jspcode=" + jspcode); } else if ('mozwebsocket' in window) { websocket = new mozwebsocket("ws://" + path + "wsmy?jspcode=" + jspcode); } else { websocket = new sockjs("http://" + path + "wsmy/sockjs?jspcode=" + jspcode); } websocket.onopen = function(event) { console.log("websocket:已连接"); console.log(event); }; websocket.onmessage = function(event) { var data = json.parse(event.data); console.log("websocket:收到一条消息-norm", data); alert("websocket:收到一条消息"); }; websocket.onerror = function(event) { console.log("websocket:发生错误 "); console.log(event); }; websocket.onclose = function(event) { console.log("websocket:已关闭"); console.log(event); } </script>
3.通过controller调用进行websocket的后台推送
/** *project name: price *file name: garlicpricecontroller.java *package name: com.yun.price.garlic.controller *date: 2016年6月23日 下午3:23:46 *copyright (c) 2016,578888218@qq.com all rights reserved. */ package com.yun.price.garlic.controller; import java.io.ioexception; import java.util.date; import java.util.list; import javax.annotation.resource; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpsession; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.responsebody; import org.springframework.web.context.request.requestcontextholder; import org.springframework.web.context.request.servletrequestattributes; import org.springframework.web.servlet.modelandview; import org.springframework.web.socket.textmessage; import com.google.gson.gsonbuilder; import com.yun.common.entity.datagrid; import com.yun.price.garlic.dao.entity.garlicprice; import com.yun.price.garlic.model.garlicpricemodel; import com.yun.price.garlic.service.garlicpriceservice; import com.yun.websocket.mywebsockethandler; /** * title: garlicpricecontroller<br/> * description: * * @company: 青岛励图高科<br/> * @author: 刘云生 * @version: v1.0 * @since: jdk 1.7.0_80 * @date: 2016年6月23日 下午3:23:46 <br/> */ @controller public class garlicpricecontroller { @resource mywebsockethandler mywebsockethandler; @requestmapping(value = "garlicpricecontroller/testwebsocket", method ={requestmethod.post,requestmethod.get}, produces = "application/json; charset=utf-8") @responsebody public string testwebsocket() throws ioexception{ mywebsockethandler.sendmessagetojsp(new textmessage(new gsonbuilder().create().tojson("\"number\":\""+"garlicpricecontroller/testwebsocket"+"\"")), "aaa"); return "1"; } }
4.所用到的jar包
<dependency> <groupid>org.springframework</groupid> <artifactid>spring-websocket</artifactid> <version>4.0.1.release</version> </dependency>
5.运行的环境
至少tomcat8.0以上版本,否则可能报错
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。