บทความนี้แชร์ WebSocket แบบรวม SpringMVC ของคุณเพื่อใช้การส่งข้อความสำหรับการอ้างอิงของคุณ เนื้อหาเฉพาะมีดังนี้
1. สร้างพื้นหลังสำหรับ WebSocket Handshake Protocol
(1) คลาสการใช้งานการจับมือกัน
/** *ชื่อโครงการ: ราคา *ชื่อไฟล์: handshake.java *ชื่อแพ็คเกจ: com.yun.websocket *วันที่: 3 กันยายน 2016 เวลา 4:44:27 PM *ลิขสิทธิ์ (c) 2016,[email protected] */ แพ็คเกจ 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; /** *หัวข้อ: Handshake <br/> *คำอธิบาย: *@Company: Qingdao Litu Hi-Tech <br/> *@ผู้แต่ง: Liu Yunsheng *@เวอร์ชัน: v1.0 *@ตั้งแต่: JDK 1.7.0_80 *@วันที่: 3 กันยายน 2016 เวลา 4:44:27 PM ก่อนหน้านี้ (คำขอ serverhttprequest, serverhttpresponse การตอบสนอง, websockethandler wshandler, แผนที่ <สตริง, วัตถุ> แอตทริบิวต์) โยนข้อยกเว้น {// todo วิธีการที่สร้างอัตโนมัติ stub string jspcode = (servletserverhttprequest). // แท็กผู้ใช้ // string userId = (string) เซสชัน. getAttribute ("userId"); if (jSpCode! = null) {attributes.put ("jspCode", jSpCode); } else {return false; } return true; } @Override โมฆะสาธารณะ Afterhandshake (คำขอ serverhttprequest, การตอบสนอง serverhttpresponse, websockethandler wshandler, ข้อยกเว้นข้อยกเว้น) {// วิธีการที่สร้างอัตโนมัติ stub}}}}}
(2) คลาสการใช้งาน MyWebSocketConfig
/** *ชื่อโครงการ: ราคา *ชื่อไฟล์: mywebsocketConfig.java *ชื่อแพ็คเกจ: com.yun.websocket *วันที่: 3 กันยายน 2016 เวลา 4:52:29 PM *ลิขสิทธิ์ (c) 2016,[email protected] สงวนลิขสิทธิ์ */ แพ็คเกจ 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; /** *title: mywebsocketconfig <br/> *คำอธิบาย: *@บริษัท : Qingdao litu hi-tech <br/> *@ผู้แต่ง: liu yunsheng *@@เวอร์ชัน: v1.0 *@ตั้งแต่: jdk 1.7.0_80 *@วันที่: 3 กันยายน 2016 เวลา 4:52:29 MyWebSocketConfig ขยาย WebMVCCONFigurerAdapter ใช้ WebSocketConfigurer {@Resource MyWebsockethandler Handler; @Override โมฆะสาธารณะ registerwebsockethandlers (WebSocketHandlerRegistry Registry) {// วิธีการที่สร้างขึ้นอัตโนมัติ registry registry.addhandler (Handler, "/wsmy") registry.addhandler (Handler, "/wsmy/sockjs").addinterceptors(New Handshake ()). withsockjs (); -
(3) คลาสการใช้งาน MyWebSockethandler
/** *ชื่อโครงการ: ราคา *ชื่อไฟล์: mywebsockethandler.java *ชื่อแพ็คเกจ: com.yun.websocket *วันที่: 3 กันยายน 2016 เวลา 4:55:12 น. *ลิขสิทธิ์ (c) 2016,[email protected] สงวนลิขสิทธิ์ */ แพ็คเกจ 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/> *คำอธิบาย: *@Company: Qingdao litu hi-tech <br/> *@ผู้แต่ง: liu yunsheng *@@เวอร์ชัน: v1.0 *@ตั้งแต่: JDK 1.7.0_80 *@วันที่: 3 กันยายน 2016 ที่ 4:55:12 PM <brb/ แผนที่สุดท้ายคงที่ <String, WebSocketSession> UsersocketSessionMap; Static {usersocketSessionMap = new hashmap <string, websocketSession> (); } @Override โมฆะสาธารณะ AfterConnectEdEstablished (เซสชัน WebSocketSession) พ่นข้อยกเว้น {// วิธีการที่สร้างอัตโนมัติแบบอัตโนมัติ Stub String String jspCode = (String) Session.getHandshakeattributes () Get ("JSPCode"); if (usersocketSessionMap.get (jSpCode) == null) {usercersocketSessionMap.put (jspCode, เซสชัน); } สำหรับ (int i = 0; i <10; i ++) {// ออกอากาศ (textMessage ใหม่ (ใหม่ gsonBuilder (). สร้าง (). tojson ("/" number/":/"+i+"/" ")); gsonBuilder (). สร้าง (). tojson ("/" number/":/"+i+"/" "))); }} @Override โมฆะสาธารณะ handleMessage (เซสชัน WebSocketSession, WebSocketMessage <?> ข้อความ) โยนข้อยกเว้น {// todo วิธีการที่สร้างขึ้นอัตโนมัติ stub // ข้อความ msg = new GSON (). fromJSON //msg.setDate( วันที่ใหม่ ()); // sendmessagetouser (msg.getto (), textMessage ใหม่ (ใหม่ gsonBuilder (). setDateFormat ("yyyy-mm-dd hh: mm: ss") สร้าง (). tojson (msg)); session.sendMessage (ข้อความ); } @Override โมฆะสาธารณะ handletRansporterRor (เซสชัน WebSocketSession, ข้อยกเว้นแบบโยนได้) โยนข้อยกเว้น {// TODO วิธีการที่สร้างขึ้นอัตโนมัติ stub ถ้า (session.isopen ()) {session.close (); } iterator <entry <string, websocketSession >> it = useroscedetsessionMap .entryset (). iterator (); // ลบเซสชันซ็อกเก็ตในขณะที่ (it.hasnext ()) {entry <string, websocketSession> entry = it.next (); if (entry.getValue (). getId (). equals (session.getId ())) {useroscyOctessionMap.remove (entry.getKey ()); System.out.println ("เซสชันซ็อกเก็ตถูกลบออกแล้ว: ID ผู้ใช้" + entry.getKey ()); หยุดพัก; }}} @Override โมฆะสาธารณะ AfterConnectionClosed (เซสชัน WebSocketSession, ClosESTATUS CloseStatus) โยนข้อยกเว้น {// todo วิธีการที่สร้างขึ้นอัตโนมัติระบบ Stub System.out.println ("WebSocket:" + session.getId () + "ปิด"); Iterator <entry <string, webSocketSession >> it = usersocketSessionMap .ENTRYSET (). iterator (); // ลบเซสชันซ็อกเก็ตในขณะที่ (it.hasnext ()) {entry <string, websocketSession> entry = it.next (); if (entry.getValue (). getId (). equals (session.getId ())) {useroscyOctessionMap.remove (entry.getKey ()); System.out.println ("เซสชันซ็อกเก็ตถูกลบออกแล้ว: ID ผู้ใช้" + entry.getKey ()); หยุดพัก; }}} @Override Public Boolean supportspartialMessages () {// วิธีการที่สร้างอัตโนมัติ todo stub stub return false; } / ** * bulk * @title: ออกอากาศ * @description: todo * @param: @param ข้อความ * @param: @throws ioexception * @return: void * @author: liu yunsheng * @date: 4:23:30 PM 10 กันยายน 2016 * WebSocketSession >> it = UsersocketSessionMap .ENTRYSET (). iterator (); // มัลติเธรดมวลส่งขณะที่ (it.hasnext ()) {รายการสุดท้าย <สตริง, websocketSession> รายการ = it.next (); if (entry.getValue (). isopen ()) {เธรดใหม่ (ใหม่ runnable () {void public void run () {ลอง {ถ้า (entry.getValue (). isopen ()) {entry.getValue () sendMessage (ข้อความ); }}}} / ** * ส่งข้อความไปยังหน้าตรวจสอบวิศวกรรมแบบเรียลไทม์ของผู้ใช้ออนไลน์ทั้งหมด * * @param ข้อความ * @throws ioexception * / โมฆะสาธารณะ sendmessagetojsp (ข้อความข้อความสุดท้าย, ประเภทสตริง) โยน ioexception // มัลติเธรดมวลการส่งในขณะที่ (it.hasnext ()) {รายการสุดท้าย <string, websocketSession> entry = it.next (); if (entry.getValue (). isopen () && entry.getKey (). มี (type)) {เธรดใหม่ (ใหม่ runnable () {โมฆะสาธารณะ run () {ลอง {ถ้า (entry.getValue () isopen () {entry.getValue () } }).เริ่ม(); -
2. สร้างแผนกต้อนรับสำหรับการประมวลผล Handshake 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' ในหน้าต่าง) {webSocket = ใหม่ webSocket ("ws: //" + path + "wsmy? jspcode =" + jspcode); } อื่นถ้า ('mozwebsocket' ในหน้าต่าง) {webSocket = ใหม่ mozwebsocket ("ws: //" + path + "wsmy? jspcode =" + jspcode); } else {webSocket = sockjs ใหม่ ("http: //" + path + "wsmy/sockjs? jspcode =" + jspcode); } webSocket.OnOpen = ฟังก์ชั่น (เหตุการณ์) {console.log ("WebSocket: Connected"); console.log (เหตุการณ์); - WebSocket.onMessage = ฟังก์ชั่น (เหตุการณ์) {var data = json.parse (event.data); console.log ("WebSocket: ได้รับข้อความ -norm", ข้อมูล); การแจ้งเตือน ("WebSocket: ได้รับข้อความ"); - websocket.onerror = function (เหตุการณ์) {console.log ("websocket: เกิดข้อผิดพลาด"); console.log (เหตุการณ์); - websocket.onclose = function (เหตุการณ์) {console.log ("websocket: close"); console.log (เหตุการณ์); } </script>3. พื้นหลัง WebSocket ผ่านการโทรคอนโทรลเลอร์
/** *ชื่อโครงการ: ราคา *ชื่อไฟล์: GarlicPriceController.java *ชื่อแพ็คเกจ: com.yun.price.garlic.controller *วันที่: 23 มิถุนายน 2016 เวลา 3:23:46 น. *ลิขสิทธิ์ (C) 2016,[email protected] */ แพ็คเกจ 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.garlicpricemodel; นำเข้า com.yun.price.garlic.service.garlicpriceservice; นำเข้า 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: 23 มิถุนายน 2016 GarlicPriceController {@Resource MyWebsockethandler MyWebsockethandler; @RequestMapping (value = "GarlicPriceController/testWebSocket", method = {requestMethod.post, requestMethod.get}, ผลิต = "แอปพลิเคชัน/json; charset = utf-8") @ResponSbody String String Public String () gsonBuilder (). create (). tojson ("/" number/":/"+"garlicpricecontroller/testwebsocket"+"/" "))," AAA "); return" 1 ";}}}
4. แพ็คเกจ jar ที่ใช้
<Effercing> <roupID> org.springframework </groupId> <ratifactid> Spring-Websocket </artifactId> <version> 4.0.1.release </version>
5. สภาพแวดล้อมการดำเนินการ
อย่างน้อย tomcat8.0 ขึ้นไปมิฉะนั้นอาจมีการรายงานข้อผิดพลาด
ข้างต้นเป็นเนื้อหาทั้งหมดของบทความนี้ ฉันหวังว่ามันจะเป็นประโยชน์ต่อการเรียนรู้ของทุกคนและฉันหวังว่าทุกคนจะสนับสนุน wulin.com มากขึ้น