Пример push websocket в режиме реального времени, написанный на основе Spring Framework, конкретный контент заключается в следующем
Шаг 1: Создайте проект Springmvc самостоятельно, он очень просто, доступен на Baidu Online; Добавьте следующий файл POM:
<!-websocket-> <dehyedency> <groupid> org.springframework </GroupId> <straCactId> Spring-websocket </artifactid> <sersive> 4.2.4.Release </version> </artifactiD> <dependence> <groupid> org.springframework </GroupId> <strifactId> </artifactide> 4. </Зависимость>
Моя весенняя версия 4.2.4, поэтому WebSocket также 4.2.4; Лучше всего сохранить то же самое, что и весенняя версия
Шаг 2: Напишите процессор сообщений
/**! * */ package com.zsy.websocket; импортировать java.io.ioexception; импортировать java.util.map; импортировать java.util.set; импортировать java.util.concurrent.concurrenthashmap; Импорт org.apache.commons.lang3.stringutils; Импорт 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; /** * ClassName: MyMessageHandler * Функция: Реализуйте интерфейс WebScoket * Дата: 31 января 2018 года в 11:10:03 AM * @author Zhaoshouyun * @version * @since jdk 1.7 */public class mymessagehandler websockethandler {// ключевой пользователь public static user asmer_key = "current_user"; / *** usermap: хранение информации об подключении пользователя WebScoket* @Since JDK 1.7*/ Private Final Static Map <String, WebSocketSession> USERMAP; static {usermap = new concurrenthashmap <string, websocketsession> (30); } /** * This method is called when closing the websocket* @see org.springframework.web.socket.WebSocketHandler#afterConnectionClosed(org.springframework.web.socket.WebSocketSession, org.springframework.web.socket.CloseStatus) */ @Override public void afterConnectionClosed(WebSocketSession session, Статус BloseStatus) Throws Exception {String userId = this.getUserid (session); if (stringutils.isnoneblank (userId)) {userMap.remove (userId); System.err.println («This» + userId + »пользователь успешно закрыт»); } else {System.err.println ("Когда закрыт, получить идентификатор пользователя пуст"); }} / **. if (stringutils.isnoneblank (userId)) {userMap.put (userId, session); session.sendmessage (новый TextMessage («Подключение к WebSocket было успешно установлено!»)); }} / *** Когда клиент вызовет websocket.send, этот метод будет вызван для передачи данных* @see org.springframework.web.socket.websockethandler#handlemessage (org.springframework.web.socket.websocketsession, org.spramework.web.socket.webocket.webockepocecess. handlemessage (сеанс WebSocketSession, WebSocketMessage <?> Сообщение) Throws Exception {String msg = message.toString (); String userId = this.getUserid (session); System.err.println ("+"+userid+"Сообщение, отправленное пользователем:"+msg); message = new TextMessage («Сервер получил сообщение, msg =»+msg); session.sendmessage (сообщение); } / *** Когда в процессе передачи возникает исключение, назовите этот метод* @see org.springframework.web.socket.websockethandler#handletransporterror (org.springframework.web.socket.websocketsession, java.lang.trowable)* @ @ @ @@override public vidletressportressessessessestorsessessession, java.lang.trowable)* @ @@override public void Throws Exception {webSocketMessage <string> message = new TextMessage ("Сообщение об исключении:"+e.getMessage ()); session.sendmessage (сообщение); } / ** * * @see org.springframework.web.socket.websockethandler#supportSpartialMessage () * / @Override public boolean supportmessages () {return false; } / ** * SendmessageToureser: отправить указанному пользователю * @author zhaoshouyun * @param userid * @param contents * @since jdk 1.7 * / public void sendmessageTouser (String userId, String Contents) {WebSocketSession Session = userMap.get (userId); if (session! = null && session.isopen ()) {try {textmessage message = new TextMessage (contents); session.sendmessage (сообщение); } catch (ioException e) {e.printstackTrace (); }}} / ** * SendmessageToallusers: отправить всем пользователям * @author zhaoshouyun * @param contents * @since jdk 1.7 * / public void sendmessagetoallusers (String contents) {set <string> userids = usermap.keyset (); for (String userId: userIds) {this.SendMessageToureser (userId, contents); }} / ** * getUserid: получить идентификатор пользователя * @author zhaoshouyun * @param session * @return * @since jdk 1.7 * / private string getUserid (websocketsession) {try {string userid = (string) session.getattributes (). get (user_key); вернуть userId; } catch (Exception e) {e.printstackTrace (); } return null; }}Шаг 3: Напишите, связанную с Websocket Configuration, конечно, вы можете настроить ее в XML; Я сейчас не использую конфигурацию XML, и я использую конфигурацию кода, и мне нужно добавить пакет сканирования в контексте XML: компонент-сканирование Base-package = "com.zsy.websocket" />
/**! * * / / ** * Имя проекта: Springrabbitmq * Имя файла: websocketconfig.java * Имя пакета: com.zsy.websocket * Дата: 13:10:33 31 января 2018 г. * Copyright (c) 2018, Zhaoshouyun Все права защищены. * */ package com.zsy.websocket; Импорт org.springframework.context.annotation.bean; Импорт org.springframework.context.annotation.configuration; импорт org.springframework.web.socket.websockethandler; Импорт org.springframework.web.socket.config.annotation.enableWebSocket; Импорт org.springframework.web.socket.config.annotation.websocketConfigurer; Импорт org.springframework.web.socket.config.annotation.websockethandlerregistry; /** * classname: websocketConfig * Функция: todo добавить функцию. * Дата: 31 января 2018 года в 13:10:33 * @author Zhaoshouyun * @version * @since jdk 1.7 * / @configuration @enablewebsocket public class websocketconfig реализует websocketcocetconfigurer { / ** * org.springframework.web.socket.config.annotation.websocketConfigurer#Registerwebsockethandlers (org.springframework.web.socket.config.annotation.websockethandlerRegistr "/testhandler").addinterceptors(new websocketInterceptor ()); Registry.addhandler (myhandler (), "/socketjs/testhandler").addinterceptors(new websocketCocketInterceptor ()). withsockjs (); } @Bean public websockethandler myhandler () {return new mymessagehandler (); }} Шаг 4: Напишите адаптер WebSocket
пакет com.zsy.websocket; импортировать java.util.map; Импорт org.springframework.http.server.serverhttprequest; Импорт org.springframework.http.server.serverhttpresponse; Импорт org.springframework.http.server.servletserverhttprequest; импорт org.springframework.web.socket.websockethandler; Import org.springframework.web.socket.server.support.httpsessionHandShakeInterceptor; /** * classname: websocketinterceptor * Функция: todo добавить функцию. * Дата: 31 января 2018 года в 11:42:34 * @author Zhaoshouyun * @version * @since jdk 1.7 * / public class websocketerceptor расширяет httpsessionhakeinterceptor { / ** * todo кратко описывает функцию реализации этого метода (необязательно). * @see org.springframework.web.socket.server.support.httpsessionHandshakeInterceptor#заранее org.springframework.web.socket.websockethandler, java.util.map) */ @override public boolean заранее (Serverhttprequest запрос, Serverhttprespons Servletserverhttprequest serverhttprequest = (servletserverhttprequest) запрос; // Получить параметр string userId = serverhttprequest .getServletRequest (). GetParameter ("userId"); attributes.put (mymessagehandler.user_key, userid); } вернуть true; }} Соответствующий JS на шаге 5:
<%@ page language = "java" contentType = "text/html; charset = iso-8859-1" pageencoding = "iso-8859-1"%> <! Doctype html public "-// w3c // dtd html 4.01 Transitional // en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <Head> <meta http-equiv = "content-type" content = "text/html; charset = iso-8859-1"> <tite> insert title здесь </title> <script type = "text/javascist"> <Tite> vAr websoctict; // сначала определить, поддерживается ли WebSocket if ('websocket' в Window) {webSocket = new WebSocket ("ws: // localhost: 8085/springtest/testhandler? Userid = zhaoshouyun"); } else if ('mozwebsocket' in window) {websocket = new mozwebsocket ("ws: // localhost: 8085/springtest/testhandler? userid = zhaoshouyun"); } else {websocket = new sockjs ("http: // localhost: 8085/springtest/socketjs/testhandler? userid = zhaoshouyun"); } // При открытии соединения, websocket.onopen = function (evnt) {console.log ("websocket.onopen"); }; // При получении сообщения, websocket.onmessage = function (evnt) {alert (evnt.data); }; websocket.onerror = function (evnt) {console.log ("websocket.onerror"); }; websocket.onclose = function (evnt) {console.log ("websocket.onclose"); }; function shows () {// Клиент активно отправляет сообщение websocket.send (document.getElementById ('msg'). Value); } </script> </head> <body> <input type = "text" value = "" id = "msg"> <button onclick = "say ()"> </button> </body> </html> Шаг 6 Тест:
пакет com.zsy.test.controller; импортировать java.util.hashmap; импортировать java.util.map; Импорт org.springframework.beans.factory.annotation.autowired; Импорт org.springframework.beans.factory.annotation.value; Import org.springframework.sterotype.controller; Импорт org.springframework.web.bind.annotation.requestbody; Импорт org.springframework.web.bind.annotation.requestmapping; Импорт org.springframework.web.bind.annotation.responsebody; Импорт com.zsy.websocket.mymessagehandler; /** * ClassName: TestController * Функция: TODO добавить функцию. * Дата: 14 декабря 2017 года в 11:11:23 * @author Zhaoshouyun * @version * @since jdk 1.7 */ @controller public class testcontroller {@autowired mymessagehandler handler; @Requestmapping ("/get") public String get () {return "index"; } @Responsebody @Requestmapping ("/get1") public String send (string name) {handler.sendmessageTouser ("zhaoshouyun", "Содержимое, отправленное сервером:"+name); вернуть "успех"; }}Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.