最新文章專題視頻專題問(wèn)答1問(wèn)答10問(wèn)答100問(wèn)答1000問(wèn)答2000關(guān)鍵字專題1關(guān)鍵字專題50關(guān)鍵字專題500關(guān)鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關(guān)鍵字專題關(guān)鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
問(wèn)答文章1 問(wèn)答文章501 問(wèn)答文章1001 問(wèn)答文章1501 問(wèn)答文章2001 問(wèn)答文章2501 問(wèn)答文章3001 問(wèn)答文章3501 問(wèn)答文章4001 問(wèn)答文章4501 問(wèn)答文章5001 問(wèn)答文章5501 問(wèn)答文章6001 問(wèn)答文章6501 問(wèn)答文章7001 問(wèn)答文章7501 問(wèn)答文章8001 問(wèn)答文章8501 問(wèn)答文章9001 問(wèn)答文章9501
當(dāng)前位置: 首頁(yè) - 科技 - 知識(shí)百科 - 正文

微信小程序 websocket 實(shí)現(xiàn)SpringMVC+Spring+Mybatis

來(lái)源:懂視網(wǎng) 責(zé)編:小采 時(shí)間:2020-11-27 22:33:18
文檔

微信小程序 websocket 實(shí)現(xiàn)SpringMVC+Spring+Mybatis

微信小程序 websocket 實(shí)現(xiàn)SpringMVC+Spring+Mybatis:微信小程序?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 --> &
推薦度:
導(dǎo)讀微信小程序 websocket 實(shí)現(xiàn)SpringMVC+Spring+Mybatis:微信小程序?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 --> &

微信小程序?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)聽(tīng)
 @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連接已打開(kāi)!')
 })
 wx.onSocketError(function (res) {
 console.log('WebSocket連接打開(kāi)失敗,請(qǐng)檢查!')
 })
 wx.onSocketMessage(function (res) {
 console.log('收到服務(wù)器內(nèi)容:' + res.data)
 })
 }
})

運(yùn)行效果

聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

微信小程序 websocket 實(shí)現(xiàn)SpringMVC+Spring+Mybatis

微信小程序 websocket 實(shí)現(xiàn)SpringMVC+Spring+Mybatis:微信小程序?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 --> &
推薦度:
  • 熱門焦點(diǎn)

最新推薦

猜你喜歡

熱門推薦

專題
Top