微信小程序實現websocket步驟:
後台:
1. 添加maven依賴 2. 創建握手 3. 創建處理器 4. spring配置(xml配置或javabean方式配置任選一種)
微信小程序:
1. 書寫連接
java後台
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.創建握手
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; /** * 此類用來獲取登錄用戶信息並交由websocket管理 */ public class MyWebSocketInterceptor implements HandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse arg1, WebSocketHandler arg2, Map<String, Object> arg3) throws Exception { // 將ServerHttpRequest轉換成request請求相關的類,用來獲取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.創建處理器
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<>(); // 用戶進入系統監聽 @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { System.out.println("成功進入了系統。。。"); users.add(session); sendMessagesToUsers(new TextMessage("今天晚上服務器維護,請注意")); } // @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { // 將消息進行轉化,因為是消息是json數據,可能裡面包含了發送給某個人的信息,所以需要用json相關的工具類處理之後再封裝成TextMessage, // 我這兒並沒有做處理,消息的封裝格式一般有{from:xxxx,to:xxxxx,msg:xxxxx},來自哪裡,發送給誰,什麼消息等等 // TextMessage msg = (TextMessage)message.getPayload(); // 給所有用戶群發消息 //sendMessagesToUsers(msg); // 給指定用戶群發消息 //sendMessageToUser(userId, msg); } // 後台錯誤信息處理方法 @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { } // 用戶退出後的處理,不如退出之後,要將用戶信息從websocket的session中remove掉,這樣用戶就處於離線狀態了,也不會占用系統資源 @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { if (session.isOpen()) { session.close(); } users.remove(session); System.out.println("安全退出了系統"); } @Override public boolean supportsPartialMessages() { return false; } /** * 給所有的用戶發送消息 */ public void sendMessagesToUsers(TextMessage message) { for (WebSocketSession user : users) { try { // isOpen()在線就發送 if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } } /** * 發送消息給指定的用戶 */ public void sendMessageToUser(String userId, TextMessage message) { for (WebSocketSession user : users) { if (user.getAttributes().get("").equals(userId)) { try { // isOpen()在線就發送 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的後綴,是因為web.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(“*”)中的*代表合法的請求域名,該方法接受一個可變數組作為參數,一定要配置,不然會請求時會出現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({ /** * 頁面的初始數據 */ 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連接打開失敗,請檢查!') }) wx.onSocketMessage(function (res) { console.log('收到服務器內容:' + res.data) }) } })
運行效果
以上就是微信小程序 後台的建立,如有疑問請留言或者到本站社區交流討論,本站關於微信小程序的文章還有很多,希望大家多多搜索查閱,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!