이 기사는 귀하와 공유하여 SpringMVC 통합 WebSocket을 공유하여 참조를위한 메시지 푸시를 구현합니다. 특정 내용은 다음과 같습니다
1. WebSocket 핸드 셰이크 프로토콜에 대한 배경을 만듭니다
(1) 핸드 셰이크 구현 클래스
/** *프로젝트 이름 : 가격 *파일 이름 : handshake.java *패키지 이름 : com.yun.websocket *날짜 : 2016 년 9 월 3 일 오후 4:44:27 *저작권 (c) 2016,[email protected] 판권 소유. */ 패키지 com.yun.websocket; java.util.map import; org.springframework.http.server.serverhttprequest; org.springframework.http.server.serverhttpresponse; import org.springframework.http.server.servletserverhttprequest; org.springframework.web.socket.websockethandler; org.springframework.web.socket.server.handshakeinterceptor; /** *제목 : 핸드 셰이크 <br/> *설명 : *@Company : Qingdao litu hi-tech <br/> *@저자 : liu yunsheng *@version : v1.0 *@rid : jdk 1.7.0_80 *@date : 2016 년 9 월 3 일 4:44:27 pm <br/> */public class handshake handshake intercector handshincercecececeper a handshaine 사전 핸드 셰이크 (ServerHttpRequest 요청, ServerHttPresponse 응답, WebSocketHandler WSHandler, MAP <String, Object> Attributes) 예외 {// todo auto-auto-auto-auto-auto-auto-autttprequest). // tag user // string userId = (string) session.getAttribute ( "userId"); if (jspcode! = null) {attributes.put ( "jspcode", jspcode); } else {return false; } true를 반환합니다. } @override public void aquhandshake (serverhttprequest request, serverhttpresponse 응답, websockethandler wshandler, 예외 예외) {// todo 자동 생성 메소드 stub}}}}
(2) MyWebSocketConfig 구현 클래스
/** *프로젝트 이름 : 가격 *파일 이름 : MyWebSocketConfig.java *패키지 이름 : com.yun.websocket *날짜 : 2016 년 9 월 3 일 오후 4:52:29 *Copyright (C) 2016,[email protected] 모든 권리 보유. */ 패키지 com.yun.websocket; import javax.annotation.resource; org.springframework.stereotyp.component import; 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; import org.springframework.web.socket.config.annotation.websockethandlerregistry; /** *제목 : MyWebSocketConfig <br/> *설명 : *@Company : Qingdao litu Hi-Tech <br/> *@저자 : Liu Yunsheng *@version : v1.0 *@ress : jdk 1.7.0_80 *@date : 9 월 3 일 오후 4시 52 분 <br classe @component @components @components MyWebSocketConfig 확장 webmvcconfigureradapter는 WebSocketConfigurer {@Resource MyWebSocketHandler handler; @override public void registerwebsockethandlers (websockethandlerregistry registry) {// todo auto-auto-regenated method stub registry.addhandler (handler, "/wsmy").addinterceptors(new handshake ()); registry.addhandler (handler, "/wsmy/sockjs").addinterceptors(new handshake ()). withsockjs (); }}
(3) MyWebsockethandler 구현 클래스
/** *프로젝트 이름 : 가격 *파일 이름 : MyWebSocketHandler.java *패키지 이름 : com.yun.websocket *날짜 : 2016 년 9 월 3 일 오후 4:55:12 *Copyright (C) 2016,[email protected] 모든 권리 보유. */ 패키지 com.yun.websocket; import java.io.ioexception; java.util.hashmap import; import java.util.iterator; java.util.map import; Java.util.map.entry 가져 오기; org.springframework.stereotyp.component import; import org.springframework.web.socket.closestatus; org.springframework.web.socket.textmessage import; org.springframework.web.socket.websockethandler; import org.springframework.web.socket.websocketmessage; org.springframework.web.socket.websocketsession import; import com.google.gson.gsonBuilder; /** *제목 : MyWebSocketHandler <br/> *설명 : *@Company : Qingdao Litu Hi-Tech <br/> *@저자 : Liu Yunsheng *@version : v1.0 *@reat : jdk 1.7.0_80 *@date : 9 월 3 일 오후 3시 {/@component public classion mywockethandler websockender webockender and websockender and websockender public classe : jdk 1.7.0_80 *@ 최종지도 <String, WebSocketSession> userocketSessionMap; static {userocketsessionmap = new Hashmap <string, websocketSession> (); } @override public void afterconnectionestablished (websocketSession session) 예외 {// todo auto-auto-a-auto-regenated method stub jspcode = (string) session.gethandshakeattributes (). get ( "jspcode"); if (userocketsessionmap.get (jspcode) == null) {userocketsessionmap.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, webSocketSession <?> message) 예외를 {// todo auto-auto-regenated 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 (메시지); } @override public void handletransporterror (websocketSession 세션, 던질 수있는 예외) 예외 {// todo 자동 생성 메소드 스터브 if (session.isopen ()) {session.close (); } iterator <enly <string, webSocketSession >> it = userocketSessionMap .EntRySet (). iterator (); // 소켓 세션을 제거하는 동안 (it.hasnext ()) {enther <string, webSocketSession> entry = it.next (); if (Entry.GetValue (). getId (). equals (session.getId ())) {userocketSessionMap.remove (endre.getKey ()); System.out.println ( "소켓 세션이 제거되었습니다 : user id" + enterke.getKey ()); 부서지다; }}} @override public void afterConnectionClosed (websocketSession 세션, CloseStatus closeStatus) 예외 {// todo auto-auto-auto-auto-auto-auto-auto-auto-auto-autoceated method.out.println ( "websocket :" + session.getid () + "close"); iterator <eptry <string, websocketSession >> it = userocketSessionMap .EntRySet (). iterator (); // 소켓 세션을 제거하는 동안 (it.hasnext ()) {enther <string, webSocketSession> entry = it.next (); if (Entry.GetValue (). getId (). equals (session.getId ())) {userocketSessionMap.remove (endre.getKey ()); System.out.println ( "소켓 세션이 제거되었습니다 : user id" + enterke.getKey ()); 부서지다; }}} @override public boolean supportspartialmessages () {// todo 자동 생성 메소드 스터브 return false; } / ** * bulk * @title : broadcast * @description : todo * @param : @param message * @param : @throws ioexception * @Throws : void * @author : liu yunsheng * @date : 4:23:30 PM * 9 월 10 일 * @Throws * / public void void <atterator {throwestor {throwelecement <terator <terater <terator <terator <terator WebSocketSession >> it = userocketSessionMap .EntRySet (). iterator (); // multithreading mass 송신기 (it.hasnext ()) {최종 항목 <String, webSocketSession> entry = it.next (); if (enther.getValue (). isopen ()) {new 스레드 (new runnable () {public void run () {try (retty. }}}}} / ** * 모든 온라인 사용자의 실시간 엔지니어링 검사 페이지에 메시지를 보내십시오 * * @param 메시지 * @throws ioexception * / public void sendMessagetojsp (최종 TextMessage 메시지, 문자열 유형) ioException {iterator <enther <string, webSocketSession >> userOCTESSINGMAP. // multithreaded mass 송신기 (it.hasnext ()) {Final Entry <String, webSocketSession> entry = it.next (); if (Entry.getValue (). isopen () && entry.getKey (). conture (type)) {new Thread (new runnable () {public void run () {try (retty.getValue (). isopen ()) {enther.getValue (). sendMessage (메시지); } }).시작(); }}}}}}
2. WebSocket 핸드 셰이크 처리를위한 프론트 데스크를 만듭니다
<cript> var path = '<%= Basepath%>'; var userid = 'lys'; if (userId == -1) {wind } var jspcode = userId+"_ aaa"; var websocket; if (Window의 'WebSocket') {WebSocket = new WebSocket ( "ws : //" + path + "wsmy? jspcode =" + jspcode); } else if (창에 'mozwebsocket') {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 : Error가 발생"); Console.log (이벤트); }; WebSocket.onClose = function (event) {console.log ( "WebSocket : Close"); Console.log (이벤트); } </스크립트>3. WebSocket 배경 컨트롤러 호출을 푸시합니다
/** *프로젝트 이름 : 가격 *파일 이름 : GarlicPriceController.java *패키지 이름 : com.yun.price.garlic.controller *날짜 : 2016 년 6 월 23 일 오후 3시 23 분 46 초 *Copyright (C) 2016,[email protected] All Rights Reserved. */ 패키지 com.yun.price.garlic.controller; import java.io.ioexception; import java.util.date; Java.util.list 가져 오기; import javax.annotation.resource; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpsession; org.springframework.beans.factory.annotation.autowired; org.springframework.stereotyp.controller import; org.springframework.web.bind.annotation.requestmapping; org.springframework.web.bind.annotation.requestmethod; org.springframework.web.bind.annotation.responsebody; org.springframework.web.context.request.RequestContexTholder; org.springframework.web.context.request.servletrequestattributes; org.springframework.web.servlet.modelandview import; org.springframework.web.socket.textmessage import; 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; /** * 제목 : GarlicPriceController <br/> * 설명 : * * @company : Qingdao litu hi-tech <br/> * @author : liu yunsheng * @version : v1.0 * @since : jdk 1.7.0_80 * @date : 2016 년 6 월 23 일, 3 월 23:46 pm <br/ @contoller roller GarlicPriceController {@Resource MyWebSocketHandler MyWebsocketHandler; @requestmapping (value = "value ="garlicpricecontroller/testwebsocket ", method = {requestmethod.post, requestmethod.get}, produces ="application/json; charset = utf-8 ") @ResponseBody public string testwebsocket () ioxception (mywebeskEction) {mywebsockethandler.sendmessagetojsp gsonBuilder (). create (). tojson ( "/"number/":/"+"+"garlicpricecontroller/testwebsocket "+"/"")), "aaa"); return "1";}}
4. 사용 된 항아리 패키지
<pectionency> <groupid> org.springframework </groupid> <artifactid> Spring-websocket </artifactid> <버전> 4.0.1. Release </version> </fectionency>
5. 운영 환경
최소한 tomcat8.0 이상, 그렇지 않으면 오류 가보고 될 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.