Эта статья делится с вами SpringMVC Integrated WebSocket для реализации push для вашей ссылки. Конкретный контент заключается в следующем
1. Создайте фон для протокола рукопожатия WebSocket
(1) Класс реализации рукопожатия
/**! */ package com.yun.websocket; импортировать java.util.map; Импорт org.springframework.http.server.serverhttprequest; Импорт org.springframework.http.server.serverhttpresponse; Импорт org.springframework.http.server.servletserverhttprequest; импорт org.springframework.web.socket.websockethandler; Импорт org.springframework.web.socket.server.handshakeinterceptor; /** *Title: HandShake<br/> *Description: *@Company: Qingdao Litu Hi-Tech<br/> *@author: Liu Yunsheng*@version: v1.0 *@since: JDK 1.7.0_80 *@Date: September 3, 2016 at 4:44:27 pm <br/> */ public class HandShake implements HandshakeInterceptor{ @Override public boolean Предварительное расположение (Serverhttprequest, Serverhttpresponse ответ, WebSockethandler Wshandler, Map <String, Object> Attributes) Throws Exception {// todo автоматически генерируемый метод stub string jspcode = ((servletserverhtprequest). // тег пользователя // string userId = (string) session.getAttribute ("userId"); if (jspcode! = null) {attributes.put ("jspcode", jspcode); } else {return false; } вернуть true; } @Override public void ufferhandshake (ServerHttpRequest запрос, Serverhttpresponse ответ, WebSockethandler Wshandler, Exception Exception) {// todo Автогенерированный метод stub}}(2) класс реализации MyWebSockeCocketConfig
/**! */ package com.yun.websocket; Импорт javax.annotation.resource; Import org.springframework.stereotype.component; Импорт org.springframework.web.servlet.config.annotation.enableWebMVC; Импорт org.springframework.web.servlet.config.annotation.webmvcconfigurerAdapter; Импорт org.springframework.web.socket.config.annotation.enableWebSocket; Импорт org.springframework.web.socket.config.annotation.websocketConfigurer; Импорт org.springframework.web.socket.config.annotation.websockethandlerregistry; /** *Title: MyWebSocketConfig<br/> *Description: *@Company: Qingdao Litu Hi-Tech<br/> *@author: Liu Yunsheng*@version: v1.0 *@since: JDK 1.7.0_80 *@Date: September 3, 2016 at 4:52:29 pm <br/> */ @Component @EnableWebMvc @EnableWebSocket public class MyWebSockEcketConfig Extends WebMVCConfigurerAdapter реализует WebSocketConfigurer {@Resource myWebSockethandler обработчика; @Override public void RegistersWebSockethandlers (Реестр WebSockethandlerRegistry) {// Todo Auto Generated Method Stub Registry.addhandler (Handler, "/wsmy").addinterceptors(new Handshake ()); Registry.addhandler (Handler, "/wsmy/sockjs").addinterceptors(new Handshake ()). withsockjs (); }}(3) класс реализации MyWebSockethandler
/** *Имя проекта: Цена *Имя файла: mywebsockethandler.java *Имя пакета. */ package com.yun.websocket; импортировать java.io.ioexception; импортировать java.util.hashmap; импортировать java.util.iterator; импортировать java.util.map; импортировать java.util.map.entry; Import org.springframework.stereotype.component; Импорт org.springframework.web.socket.closestatus; Импорт org.springframework.web.socket.textmessage; импорт org.springframework.web.socket.websockethandler; Импорт org.springframework.web.socket.websocketmessage; Импорт org.springframework.web.socket.websocketsession; Импорт com.google.gson.gsonbuilder; /** *Название: myWebSockethandler <br/> *Описание: *@Company: Qingdao Litu Hi-Tech <br/> *@Автор: Liu Yunsheng *@версия: v1.0 *@С момента: jdk 1.7.0_80 *@Дата: 3 сентября 2016 г. в 4:55:12 <brbr/>/@component public websetheshethethethethethethethethetr окончательная карта <строка, websocketsession> usersocketsessionMap; static {usersocketsessionMap = new HashMap <String, WebSocketSession> (); } @Override public void efferConceSectabledicated (сеанс WebSocketSession) Throws Exception {// TODO Auto Generated Method String String jspcode = (String) session.gethandshakeattributes (). Get ("jspcode"); if (usersocketsessionMap.get (jspcode) == null) {userocketsessionMap.put (jspcode, session); } for (int i = 0; i <10; i ++) {// Froduct (new TextMessage (new GsonBuilder (). Create (). Gsonbuilder (). Create (). Tojson ("/" number/":/"+i+"/" "))); }} @Override public void handlemessage (сеанс WebSocketSession, webSocketMessage <?> Сообщение) Throws Exception {// TODO Auto Generated Method Stub // Сообщение msg = new gson (). Forjson (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 (сообщение); } @Override public void handletransporterror (сеанс WebSocketSession, выбрасываемое исключение), бросает исключение {// TODO Auto Generated Method Stub if if (session.isopen ()) {session.close (); } Iterator <entry <string, websocketsession >> it = userocketsessionMap .entrySet (). Iterator (); // Удалить сеанс сокета while (it.hasnext ()) {inpit <string, websocketsession> entry = it.next (); if (entry.getValue (). getId (). equals (session.getid ())) {userocketsessionMap.remove (entry.getKey ()); System.out.println ("Сессия сокета была удалена: идентификатор пользователя" + entry.getKey ()); перерыв; }}} @Override public void после контакта (сеанс WebSocketSession, rolseStatus closeStatus) Throws Exception {// TODO Auto Generated System System.out.println ("websocket:" + session.getid () + "close"); Iterator <entry <string, websocketsession >> it = userocketsessionMap .entrySet (). Iterator (); // Удалить сеанс сокета while (it.hasnext ()) {inpit <string, websocketsession> entry = it.next (); if (entry.getValue (). getId (). equals (session.getid ())) {userocketsessionMap.remove (entry.getKey ()); System.out.println ("Сессия сокета была удалена: идентификатор пользователя" + entry.getKey ()); перерыв; }}} @Override public boolean supportspartialmessage () {// todo автоматически генерируемый метод заглушка вернуть false; } / ** * Bulk * @title: Froadcast * @description: todo * @param: @param message * @param: @throws ioexception * @return: void * @author: liu yunsheng * @date: 4:23:30 PM на 10 сентября * @Throws * / public Broadcast (Final TextMessage) Throus Eo -exception inteex intexception strowex inteex preseex inteex preseex inteex presex introdeex Websocketsession >> it = usersocketsessionMap .EntrySet (). Iterator (); // Многопользовательская массовая отправка while (it.hasnext ()) {окончательная запись <string, websocketsession> entry = it.next (); if (entry.getValue (). isoPen ()) {new Thread (new Runnable () {public void run () {try {if (entry.getValue (). isoPen ()) {entry.getValue (). SendMessage (сообщение);}} catch (ioException e) {e.printStackTrace (); }}}} / ** * Отправить сообщение на страницу инженерного инженера в реальном времени всех онлайн-пользователей * * @param Message * @Throws ioException * / public void sendmessageTojsp (окончательное сообщение TextMessage, тип строки) Throws IoException {iterator <intpring, websocketsession >> it = unersocketsessionmap. // Многопользовательская массовая отправка while (it.hasnext ()) {окончательная запись <string, websocketsession> entry = it.next (); if (entry.getValue (). isoPen () && intry.getKey (). Содержит (type)) {new Thread (new Runnable () {public void run () {try {if (intry.getValue (). isoPen ()) {inpit.getValue (). SendMessage (message); } }).начинать(); }}}}}}2. Создайте стойку регистрации для обработки рукопожатия WebSocket
<script> var path = '<%= basepath%>'; var userid = 'lys'; if (userid ==-1) {window.location.href = "<%= basePath2%>" rel = "внешний 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: connected"); console.log (событие); }; 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 (событие); }; websocket.onclose = function (event) {console.log ("websocket: close"); console.log (событие); } </script>3. websocket facker prope через звонок контроллера
/**! */ package com.yun.price.garlic.controller; импортировать java.io.ioexception; импортировать java.util.date; импортировать java.util.list; Импорт javax.annotation.resource; Импорт javax.servlet.http.httpservletrequest; Импорт javax.servlet.http.httpsession; Импорт org.springframework.beans.factory.annotation.autowired; Import org.springframework.sterotype.controller; Импорт org.springframework.web.bind.annotation.requestmapping; Импорт org.springframework.web.bind.annotation.requestmethod; Импорт org.springframework.web.bind.annotation.responsebody; Import org.springframework.web.context.request.requestcontextholder; Импорт org.springframework.web.context.request.servletrequestattributes; Импорт org.springframework.web.servlet.modelandView; Импорт org.springframework.web.socket.textmessage; Импорт com.google.gson.gsonbuilder; Импорт com.yun.common.entity.datagrid; Импорт com.yun.price.garlic.dao.entity.garlicprice; импорт com.yun.price.garlic.model.garlicpricemodel; Импорт com.yun.price.garlic.service.garlicpriceservice; Импорт com.yun.websocket.mywebsockethandler; /** * Название: charlicPriceController <br/> * Описание: * * @company: Qingdao litu Hi-Tech <br/> * @author: liu yunsheng * @version: v1.0 * @since: jdk 1.7.0_80 * @date: 23 июня 2016 Charlicpricecontroller {@resource mywebsockethandler mywebsockethandler; @RequestMapping (value = "charlicPriceController/testWebSocket", method = {requestMethod.post, requestMethod.get}, Pruefes = "Application/json; charset = utf-8") @responsebody public Stringsocket () newexception {myWebSockethandler.sendmessageSpocke () newexcept Gsonbuilder (). Create (). Tojson ("/" number/":/"+"charlicpricecontroller/testwebsocket"+"/" "))," aaa "); return" 1 ";}}4. Используемый пакет банки
<Depective> <groupid> org.springframework </GroupId> <ArtifactId> Spring-websocket </artifactid> <sersive> 4.0.1.release </version> </depertion>
5. Оперативная среда
По крайней мере, tomcat8.0 или выше, в противном случае может быть сообщена ошибка
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.