微信小程序实现websocket步骤:
后台:
1. 添加maven依赖 2. 创建握手 3. 创建处理器 4. spring配置(xml配置或javabean方式配置任选一种)
微信小程序:
1. 书写连接
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
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
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中配置扫描包
注意:
1. /webSocketServer.action之所以要加上.action的后缀,是因为web.xmlk中配置了拦截的后缀名为.action
2 .setAllowedOrigins(“*”)中的*代表合法的请求域名,该方法接受一个可变数组作为参数,一定要配置,不然会请求时会出现403
xml方式配置(省略)
微信小程序
// 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) }) } })