تشارك هذه المقالة مع SPRINGMVC WebSocket متكاملة لتنفيذ Push Message للرجوع إليها. المحتوى المحدد كما يلي
1. قم بإنشاء خلفية لبروتوكول WebSocket Protocol
(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 ؛ /** *العنوان: المصافحة <br/> *الوصف: *@الشركة: Qingdao litu hi-tech <br/> *@المؤلف: liu yunsheng *@الإصدار: v1.0 *@منذ: riperhandshake (request serverhtprequest request ، responsedhttpresponse ، websockethandler wshandler ، map <string ، Object> statutes) يرمي الاستثناء {// todo todo method string jspcode = ((servletserverhttprequest). // tag user // string userId = (string) session.getAttribute ("userId") ؛ if (jspcode! = null) {attributes.put ("jspcode" ، jspcode) ؛ } آخر {return false ؛ } إعادة صواب ؛ } Override public void exthandshake (request serverhttprequest request ، serverhttpresponse response ، websockethandler wshandler ، استثناء استثناء) {// todo method method method}}}(2) فئة تنفيذ MyWebSocketConfig
/** *اسم المشروع: السعر *اسم الملف: MyWebSocketConfig.java *اسم الحزمة: com.yun.websocket *التاريخ: 3 سبتمبر ، 2016 في 4:52:29 PM *حقوق الطبع والنشر (C) 2016،578888218 QQ.com جميع الحقوق محفوظة. */ package com.yun.websocket ؛ استيراد javax.annotation.Resource ؛ استيراد 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 ؛ /** *العنوان: myWebSocketConfig <br/> *الوصف: *@الشركة: qingdao litu hi-tech <br/> *@المؤلف: liu yunsheng *@الإصدار: v1.0 *@منذ: jdk 1.7.0_80 *date: 3 سبتمبر ، 2016 في 4:52:29 pm <br/> MyWebSocketConfig يمتد webmvcconfigureradapter تنفذ websocketconfigurer {resource myWebsockethandler Handler ؛ Override public void registerwebsockethandlers (سجل websockethandlerRegistry) {// todo method method method registry.addhandler (handler ، "/wsmy").AddInterceptors(new Handshake ()) ؛ registry.addhandler (Handler ، "/wsmy/sockjs").AddInterceptors(new مصافحة ()). withsockjs () ؛ }}(3) فئة تنفيذ MyWebsockethandler
/** *اسم المشروع: السعر *اسم الملف: MyWebsockethandler.java *اسم الحزمة: com.yun.websocket *التاريخ: 3 سبتمبر ، 2016 في 4:55:12 PM *حقوق الطبع والنشر (C) 2016،578888218 QQ.com جميع الحقوق محفوظة. */ package com.yun.websocket ؛ استيراد java.io.ioException ؛ استيراد java.util.hashmap ؛ استيراد java.util.iterator ؛ استيراد java.util.map ؛ استيراد java.util.map.entry ؛ استيراد 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/> *الوصف: *@الشركة: Qingdao litu hi-tech <br/> *@المؤلف: liu yunsheng *@الإصدار: v1.0 *@منذ: jdk 1.7.0_80 *@التاريخ: 3 سبتمبر ، 2016 في 4:55:12 pm <br/> الخريطة النهائية <string ، websocketsession> userSoCketSessionMap ؛ static {userSoCketSessionMap = new hashmap <string ، websocketsession> () ؛ } Override public void afterconnectionStable (جلسة WebSocketSession) يلقي الاستثناء {// todo method method method string jspcode = (string) session.gethandshakeattributes (). get ("jspcode") ؛ if (userSoCketSessionMap.get (jspcode) == null) {userSoCketSessionMap.put (jspcode ، session) ؛ } لـ (int i = 0 ؛ i <10 ؛ i ++) {// broadcast (new textMessage (new gsonbuilder (). create (). gsonbuilder (). create (). tojson ("/" number/":/"+i+"/" "))) ؛ }} Override public void handlemessage (جلسة WebSocketSession ، WebSocketMessage <؟> رسالة) يلقي الاستثناء {// tode method method method // message msg = new gson (). fromjson (message.getPayload (). tostring () ، message.class) ؛ //msg.setDate(new Date ()) ؛ // sendMessageTouser (msg.getto () ، new TextMessage (new gsonbuilder (). Session.SendMessage (Message) ؛ } Override public void handletransporterror (جلسة WebSocketSession ، استثناء قابل للارتداء) يلقي الاستثناء {// todo method method method tuto if (session.isopen ()) {session.close () ؛ } iterator <intrad <string ، websocketsession >> it = userSoCketSessionMap .entrySet (). iterator () ؛ // قم بإزالة جلسة المقبس بينما (it.hasNext ()) {entry <string ، websocketsession> entry = it.next () ؛ if (enter.getValue (). getId (). equals (session.getId ())) {userSoStictessessionMap.Remove (intrad.getKey ()) ؛ system.out.println ("تمت إزالة جلسة المقبس: معرف المستخدم" + entry.getKey ()) ؛ استراحة؛ }}} @Override public void efterConnectionClosed (جلسة WebSocketSession ، Closestatus eortestatus) يلقي الاستثناء {// todo method method method system.out.println ("websocket:" + session.getid () + "close") ؛ iterator <intrad <string ، websocketsession >> it = userSoCketSessionMap .entrySet (). iterator () ؛ // قم بإزالة جلسة المقبس بينما (it.hasNext ()) {entry <string ، websocketsession> entry = it.next () ؛ if (enter.getValue (). getId (). equals (session.getId ())) {userSoStictessessionMap.Remove (intrad.getKey ()) ؛ system.out.println ("تمت إزالة جلسة المقبس: معرف المستخدم" + entry.getKey ()) ؛ استراحة؛ }}} Override Public Boolean SupportSpartialMessages () {// todo method method method stub return false ؛ } / ** * bulk * title: broadcast * description: toDo * param: param message * param: throws ioException * return: void * @author: liu yunsheng * @date: WebSocketSession >> it = userSoCketSessionMap .entrySet (). iterator () ؛ // multithreading كتلة إرسال بينما (it.hasnext ()) {الإدخال النهائي <string ، websocketsession> entry = it.next () ؛ if (Entpl.getValue (). isOpen ()) {new thread (new RunNable () {public void run () {try {if (intradvalue (). isOpen ()) {entrad.getValue (). sendMessage (message) ؛}} catch (ioexception e) { }}}} / ** * أرسل رسالة إلى صفحة التفتيش الهندسية في الوقت الفعلي لجميع المستخدمين عبر الإنترنت * * param message * throws ioException * / public void sendmessagetojsp (رسالة نصية نهائية ، نوع سلسلة) يلقي ioException // multithedced mass sending بينما (it.hasnext ()) {الإدخال النهائي <string ، websocketsession> entry = it.next () ؛ if (intrad.getValue (). isOpen () && intpl.getKey (). } }).يبدأ()؛ }}}}}}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) ؛ } آخر إذا ('mozwebsocket' في النافذة) {websocket = new mozwebsocket ("ws: //" + path + "wsmy؟ jspcode =" + jspcode) ؛ } آخر {websocket = 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: تلقي رسالة -NOMM" ، البيانات) ؛ ALERT ("WebSocket: تلقيت رسالة") ؛ } ؛ websocket.onerror = function (event) {console.log ("websocket: حدث خطأ") ؛ console.log (حدث) ؛ } ؛ websocket.onclose = function (event) {console.log ("websocket: close") ؛ console.log (حدث) ؛ } </script>3.
/** *اسم المشروع: السعر *اسم الملف: GarlicPriceController.java *اسم الحزمة: com.yun.price.garlic.controller *التاريخ: 23 يونيو ، 2016 في 3:23:46 PM *حقوق الطبع والنشر (C) 2016،[email protected] جميع الحقوق محفوظة. */ 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 ؛ استيراد org.springframework.stereotype.controller ؛ استيراد 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 ؛ استيراد 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.garlicpricpricemodel ؛ استيراد com.yun.price.garlic.service.garlicpriceservice ؛ استيراد com.yun.websocket.mywebsockethandler ؛ /** * العنوان: garlicpriceController <br/> * الوصف: * * company: Qingdao litu hi-tech <br/> {resource myWebsockethandler myWebsockethandler ؛ requestmapping (value = "garlicpriceController/testWebsocket gsonbuilder (). create ().
4. حزمة الجرة المستخدمة
<Rependency> <roupeD> org.springframework </rougeid> <StifactId> spring-websocket </stifactid> <sophy> 4.0.1.Release </version> </sependency>
5. بيئة التشغيل
على الأقل tomcat8.0 أو أعلى ، وإلا يمكن الإبلاغ عن خطأ
ما سبق هو كل محتوى هذه المقالة. آمل أن يكون ذلك مفيدًا لتعلم الجميع وآمل أن يدعم الجميع wulin.com أكثر.