小編給大家分享一下微信小程序websocket如何實(shí)現(xiàn)SpringMVC+Spring+Mybatis,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
創(chuàng)新互聯(lián)公司成立以來(lái)不斷整合自身及行業(yè)資源、不斷突破觀念以使企業(yè)策略得到完善和成熟,建立了一套“以技術(shù)為基點(diǎn),以客戶需求中心、市場(chǎng)為導(dǎo)向”的快速反應(yīng)體系。對(duì)公司的主營(yíng)項(xiàng)目,如中高端企業(yè)網(wǎng)站企劃 / 設(shè)計(jì)、行業(yè) / 企業(yè)門戶設(shè)計(jì)推廣、行業(yè)門戶平臺(tái)運(yùn)營(yíng)、app軟件開發(fā)公司、成都手機(jī)網(wǎng)站制作、微信網(wǎng)站制作、軟件開發(fā)、服務(wù)器托管機(jī)柜等實(shí)行標(biāo)準(zhǔn)化操作,讓客戶可以直觀的預(yù)知到從創(chuàng)新互聯(lián)公司可以獲得的服務(wù)效果。
微信小程序?qū)崿F(xiàn)websocket步驟:
后臺(tái):
1. 添加maven依賴 2. 創(chuàng)建握手 3. 創(chuàng)建處理器 4. spring配置(xml配置或javabean方式配置任選一種)
微信小程序:
1. 書寫連接
java后臺(tái)
1.添加maven依賴
<!-- websocket --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>${spring.version}</version> </dependency> <!-- 其中spring版本 --> <!-- 注意spring版本一定要為4以上版本 --> <spring.version>4.3.7.RELEASE</spring.version>
2.創(chuàng)建握手
package com.ahutshop.websocket; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.HandshakeInterceptor; /** * 此類用來(lái)獲取登錄用戶信息并交由websocket管理 */ public class MyWebSocketInterceptor implements HandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse arg1, WebSocketHandler arg2, Map<String, Object> arg3) throws Exception { // 將ServerHttpRequest轉(zhuǎn)換成request請(qǐng)求相關(guān)的類,用來(lái)獲取request域中的用戶信息 if (request instanceof ServletServerHttpRequest) { ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request; HttpServletRequest httpRequest = servletRequest.getServletRequest(); } System.out.println("連接到我了"); return true; } @Override public void afterHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1, WebSocketHandler arg2, Exception arg3) { // TODO Auto-generated method stub } }
3.創(chuàng)建處理器
package com.ahutshop.websocket; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; public class WebSocketPushHandler implements WebSocketHandler { private static final List<WebSocketSession> users = new ArrayList<>(); // 用戶進(jìn)入系統(tǒng)監(jiān)聽 @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { System.out.println("成功進(jìn)入了系統(tǒng)。。。"); users.add(session); sendMessagesToUsers(new TextMessage("今天晚上服務(wù)器維護(hù),請(qǐng)注意")); } // @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { // 將消息進(jìn)行轉(zhuǎn)化,因?yàn)槭窍⑹莏son數(shù)據(jù),可能里面包含了發(fā)送給某個(gè)人的信息,所以需要用json相關(guān)的工具類處理之后再封裝成TextMessage, // 我這兒并沒(méi)有做處理,消息的封裝格式一般有{from:xxxx,to:xxxxx,msg:xxxxx},來(lái)自哪里,發(fā)送給誰(shuí),什么消息等等 // TextMessage msg = (TextMessage)message.getPayload(); // 給所有用戶群發(fā)消息 //sendMessagesToUsers(msg); // 給指定用戶群發(fā)消息 //sendMessageToUser(userId, msg); } // 后臺(tái)錯(cuò)誤信息處理方法 @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { } // 用戶退出后的處理,不如退出之后,要將用戶信息從websocket的session中remove掉,這樣用戶就處于離線狀態(tài)了,也不會(huì)占用系統(tǒng)資源 @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { if (session.isOpen()) { session.close(); } users.remove(session); System.out.println("安全退出了系統(tǒng)"); } @Override public boolean supportsPartialMessages() { return false; } /** * 給所有的用戶發(fā)送消息 */ public void sendMessagesToUsers(TextMessage message) { for (WebSocketSession user : users) { try { // isOpen()在線就發(fā)送 if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } } /** * 發(fā)送消息給指定的用戶 */ public void sendMessageToUser(String userId, TextMessage message) { for (WebSocketSession user : users) { if (user.getAttributes().get("").equals(userId)) { try { // isOpen()在線就發(fā)送 if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } } } }
4.spring配置
javabean方式配置(推薦) package com.ahutshop.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(WebSocketPushHandler(), "/webSocketServer.action").addInterceptors(new MyWebSocketInterceptor()).setAllowedOrigins("*"); registry.addHandler(WebSocketPushHandler(), "/sockjs/webSocketServer.action") .addInterceptors(new MyWebSocketInterceptor()).withSockJS(); } @Bean public WebSocketHandler WebSocketPushHandler() { return new WebSocketPushHandler(); } } spring.xml中配置掃描包 <!-- 掃描包 --> <context:component-scan base-package="com.ahutshop.websocket" />
注意:
1. /webSocketServer.action之所以要加上.action的后綴,是因?yàn)閣eb.xmlk中配置了攔截的后綴名為.action
<!-- springmvc模塊 --> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <!-- 支持異步 --> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping>
2 .setAllowedOrigins(“*”)中的*代表合法的請(qǐng)求域名,該方法接受一個(gè)可變數(shù)組作為參數(shù),一定要配置,不然會(huì)請(qǐng)求時(shí)會(huì)出現(xiàn)403
xml方式配置(省略)
微信小程序
1.websocket.wxml
<!--pages/websocket/websocket.wxml--> <view class="page"> <view class="page__hd"> </view> <view class="page__bd"> <button bindtap="connectWebsocket" type="primary">連接websocket</button> </view> </view>
2.websocket.js
// pages/websocket/websocket.js Page({ /** * 頁(yè)面的初始數(shù)據(jù) */ data: { }, connectWebsocket: function () { wx.connectSocket({ url: 'ws://localhost:8080/AhutShop/webSocketServer.action', data: { }, header: { 'content-type': 'application/json' }, method: "GET" }) wx.onSocketOpen(function (res) { console.log('WebSocket連接已打開!') }) wx.onSocketError(function (res) { console.log('WebSocket連接打開失敗,請(qǐng)檢查!') }) wx.onSocketMessage(function (res) { console.log('收到服務(wù)器內(nèi)容:' + res.data) }) } })
運(yùn)行效果
看完了這篇文章,相信你對(duì)“微信小程序websocket如何實(shí)現(xiàn)SpringMVC+Spring+Mybatis”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
網(wǎng)站標(biāo)題:微信小程序websocket如何實(shí)現(xiàn)SpringMVC+Spring+Mybatis
文章轉(zhuǎn)載:http://jinyejixie.com/article24/iehgje.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、定制網(wǎng)站、、建站公司、響應(yīng)式網(wǎng)站、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)