ตัวอย่างพุชแบบเรียลไทม์ WebSocket ที่เขียนขึ้นตามกรอบฤดูใบไม้ผลิเนื้อหาเฉพาะมีดังนี้
ขั้นตอนที่ 1: สร้างโครงการ SpringMVC ด้วยตัวคุณเองมันง่ายมากมีให้บริการบน Baidu Online; เพิ่มไฟล์ POM ต่อไปนี้:
<!-WebSocket-> <การพึ่งพา> <roupId> org.springframework </groupId> <ratifactId> Spring-Websocket </artifactid> <sersion> 4.2.4.Release </Side> </การพึ่งพาอาศัยกัน> <Sersion> 4.2.4.Release </เวอร์ชัน> </predency>
เวอร์ชันฤดูใบไม้ผลิของฉันคือ 4.2.4 ดังนั้น WebSocket จึงเป็น 4.2.4; เป็นการดีที่สุดที่จะรักษาเวอร์ชันสปริงไว้
ขั้นตอนที่ 2: เขียนโปรเซสเซอร์ข้อความ
/** * ชื่อโครงการ: SpringRabBitMq * ชื่อไฟล์: MyMessageHandler.java * ชื่อแพ็คเกจ: com.zsy.websocket * วันที่: 31 มกราคม 2018 เวลา 11:10:03 น. * ลิขสิทธิ์ (c) 2018, Zhaoshouyun สงวนลิขสิทธิ์ * */ แพ็คเกจ 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 น. * @author Zhaoshouyun * @version * @Since JDK 1.7 */คลาสสาธารณะ MyMessageHandler / *** USERMAP: การจัดเก็บข้อมูลการเชื่อมต่อผู้ใช้ WebScoket* @Since JDK 1.7*/ แผนที่คงที่ส่วนตัวสุดท้าย <String, WebSocketSession> USERMAP; Static {usermap = ใหม่พร้อมกันใหม่ hashMap <string, webSocketSession> (30); } / *** วิธีนี้เรียกว่าเมื่อปิด WebSocket* @see org.springframework.web.socket.websockethandler#afterconnectionclosed (org.springframework.web.socket.websocketsession, org.springframework. AfterConnectionClosed (เซสชัน WebSocketSession, สถานะใกล้เคียง) โยนข้อยกเว้น {string userId = this.getUserId (เซสชัน); if (stringutils.isnoneblank (userId)) {usermap.remove (userId); System.err.println ("สิ่งนี้" + userId + "ผู้ใช้ถูกปิดสำเร็จ"); } else {system.err.println ("เมื่อปิดให้รับรหัสผู้ใช้ว่างเปล่า"); }} / *** วิธีนี้เรียกว่าเมื่อสร้างการเชื่อมต่อ WebSocket* @See org.springframework.web.socket.websockethandler#afterconnectableished (org.springframework.web.socket.websockets this.getUserId (เซสชัน); if (stringutils.isnoneblank (userId)) {usermap.put (userId, เซสชัน); Session.sendMessage (TextMessage ใหม่ ("การเชื่อมต่อ WebSocket ได้รับการจัดตั้งขึ้นสำเร็จ!")); }} / *** เมื่อไคลเอนต์เรียก webSocket.Send วิธีนี้จะถูกเรียกร้องให้มีการสื่อสารข้อมูล* @See org.springframework.web.socket.websockethandler#handlemessage (org.springframework.web.socket.websockets โมฆะสาธารณะ handleMessage (เซสชัน WebSocketSession, WebSocketMessage <?> ข้อความ) โยนข้อยกเว้น {สตริง msg = message.toString (); string userId = this.getUserId (เซสชัน); System.err.println ("ข้อความ"+userId+"ที่ส่งโดยผู้ใช้คือ:"+msg); message = new textMessage ("เซิร์ฟเวอร์ได้รับข้อความ, msg ="+msg); session.sendMessage (ข้อความ); } / *** เมื่อมีข้อยกเว้นเกิดขึ้นในกระบวนการส่งสัญญาณให้โทรหาวิธีนี้* @See org.springframework.web.socket.websockethandler#handletransporterror (org.springframework.web.socket.websockets throwable e) โยนข้อยกเว้น {WebSocketMessage <String> ข้อความ = new TextMessage ("ข้อความยกเว้น:"+e.getMessage ()); session.sendMessage (ข้อความ); } / ** * * @see org.springframework.web.socket.websockethandler#supportspartialMessages () * / @Override บูลีนสาธารณะสนับสนุน SupportialMessages () {กลับเท็จ; } / ** * SendMessagetouser: ส่งไปยังผู้ใช้ที่ระบุ * @author Zhaoshouyun * @param userId * @param เนื้อหา * @Since JDK 1.7 * / โมฆะสาธารณะ sendMessagetouser if (session! = null && session.isopen ()) {ลอง {textMessage message = new TextMessage (เนื้อหา); session.sendMessage (ข้อความ); } catch (ioexception e) {e.printstacktrace (); }}} / ** * SendMessagetoAllUsers: ส่งไปยังผู้ใช้ทั้งหมด * @author Zhaoshouyun * @param สารบัญ * @Since JDK 1.7 * / โมฆะสาธารณะ sendMessagetoAllusers (เนื้อหาสตริง) {ตั้งค่า <string> userIds = usermap.keyset (); สำหรับ (String userId: userIds) {this.sendMessagetouser (userId, เนื้อหา); }} / ** * getUserId: รับ ID ผู้ใช้ * @author Zhaoshouyun * @param เซสชัน * @return * @Since JDK 1.7 * / สตริงส่วนตัว getUserId (เซสชัน WebSocketSession) {ลอง {String userId = (String) เซสชัน Session.getAtTributes () ส่งคืน USERID; } catch (exception e) {e.printstacktrace (); } return null; -ขั้นตอนที่ 3: การกำหนดค่าที่เกี่ยวข้องกับ WebSocket แน่นอนคุณสามารถกำหนดค่าได้ใน XML; ตอนนี้ฉันไม่ได้ใช้การกำหนดค่า XML และฉันใช้การกำหนดค่ารหัสและฉันจำเป็นต้องเพิ่มแพ็คเกจสแกนใน XML <บริบท: Component-Scan base-package = "com.zsy.websocket" />
/** * ชื่อโครงการ: SpringRabBitMq * ชื่อไฟล์: WebSocketConfig.java * ชื่อแพ็คเกจ: com.zsy.websocket * วันที่: 1:10:33 PM เมื่อวันที่ 31 มกราคม 2018 * ลิขสิทธิ์ (c) 2018, Zhaoshouyun สงวนลิขสิทธิ์ * * / / ** * ชื่อโครงการ: SpringRabBitMq * ชื่อไฟล์: WebSocketConfig.java * ชื่อแพ็คเกจ: com.zsy.websocket * วันที่: 1:10:33 PM เมื่อวันที่ 31 มกราคม 2018 * ลิขสิทธิ์ (c) 2018, Zhaoshouyun สงวนลิขสิทธิ์ * */ แพ็คเกจ 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 PM * @author Zhaoshouyun * @Version * @Since JDK 1.7 * / @Configuration @enablewebsocket คลาสสาธารณะ WebSocketConfig ใช้ WebSocketConfigurer { / ** * org.springframework.web.socket.config.annotation.websocketconfigurer#registerwebsockethandlers (org.springframework.web.socket.config.annotation.websockethandlerregistry) registry.addhandler (myhandler (), "/testhandler").addinterceptors( ใหม่ websocketInterceptor ()); registry.addhandler (myhandler (), "/socketjs/testhandler").addinterceptors(New WebSocketInterceptor ()). withsockjs (); } @Bean สาธารณะ WebSockethandler MyHandler () {ส่งคืน 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; นำเข้า org.springframework.web.socket.server.support.httpsessionhandshakeinterceptor; /** * className: WebSocketInterceptor * ฟังก์ชั่น: TODO เพิ่มฟังก์ชั่น * วันที่: 31 มกราคม 2018 เวลา 11:42:34 น. * @author zhaoshouyun * @version * @since Jdk 1.7 * / คลาสสาธารณะ WebSocketInterceptor ขยาย httpsessionhandshakeinterceptor { / ** * * @see org.springframework.web.socket.server.support.httpsessionhandshakeinterceptor#ล่วงหน้า (org.springframework.http.server.serverhtttprequest org.springframework.web.socket.websockethandler, java.util.map) */ @Override บูลีนสาธารณะก่อนหน้า (Serverhttprequest Request, Serverhttpresponse, servletof, websockethler wshandler, แผนที่ servletserverhttprequest serverhttprequest = (servletserverhttprequest) คำขอ; // รับพารามิเตอร์สตริง userid = serverhttprequest .getServletRequest (). getParameter ("userId"); Attributes.put (myMessageHandler.USER_KEY, USERID); } return true; - JS ที่สอดคล้องกันในขั้นตอนที่ 5:
<%@ page language = "java" contentType = "ข้อความ/html; charset = iso-8859-1" pageencoding = "iso-8859-1"%> <! "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv = "content-type" content = "text/html; charset = iso-8859-1" // ก่อนอื่นตรวจสอบว่า websocket ได้รับการสนับสนุนหรือไม่หาก ('websocket' ในหน้าต่าง) {websocket = ใหม่ websocket ("ws: // localhost: 8085/springtest/testhandler? userid = zhaoshouyun"); } อื่นถ้า ('mozwebsocket' ในหน้าต่าง) {webSocket = ใหม่ mozwebsocket ("ws: // localhost: 8085/springtest/testhandler? userid = zhaoshouyun"); } else {webSocket = sockjs ใหม่ ("http: // localhost: 8085/springtest/socketjs/testhandler? userid = zhaoshouyun"); } // เมื่อเปิดการเชื่อมต่อ, websocket.onopen = function (evnt) {console.log ("websocket.onopen"); - // เมื่อได้รับข้อความ websocket.onMessage = ฟังก์ชั่น (evnt) {แจ้งเตือน (evnt.data); - websocket.onerror = function (evnt) {console.log ("websocket.onerror"); - websocket.onclose = function (evnt) {console.log ("websocket.onclose"); - ฟังก์ชั่นบอกว่า () {// ไคลเอนต์ส่งข้อความ websocket.send (document.getElementById ('msg') ค่า); } </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; นำเข้า org.springframework.stereotype.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 คลาสสาธารณะ TestController {@autowired MyMessageHandler Handler; @RequestMapping ("/get") สตริงสาธารณะรับ () {return "ดัชนี"; } @ResponseBody @requestmapping ("/get1") สตริงสาธารณะส่ง (ชื่อสตริง) {handler.sendmessagetouser ("zhaoshouyun", "เนื้อหาที่ส่งโดยเซิร์ฟเวอร์:"+ชื่อ); กลับ "ความสำเร็จ"; -ข้างต้นเป็นเนื้อหาทั้งหมดของบทความนี้ ฉันหวังว่ามันจะเป็นประโยชน์ต่อการเรียนรู้ของทุกคนและฉันหวังว่าทุกคนจะสนับสนุน wulin.com มากขึ้น