ssm集成websocket扫码沙箱支付回调

我是基于这一篇博客springboot集成websocket来搞的,奈何能碰上的bug基本都碰上了,

bug展览​​​​​​

下面为完整的测试通过的代码。

1.引入依赖(不加这个scope会报Caused by: java.lang.ClassCastException: org.apache.tomcat.websocket.server.WsServerContainer cannot be cast to javax.websocket.server.ServerContainer)

       <!--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>
        <!-- scope注意一下-->
        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.1</version>
            <scope>provided</scope>
        </dependency>

2.websocket配置类(注意,将ServerEndpointExporter注掉,否则会报Caused by: javax.websocket.DeploymentException: Multiple Endpoints may not be deployed to the same path [/bindingRecord],因为tomcat本身已经集成了,会冲突)

@Component
@ServerEndpoint("/bindingRecord")
@Slf4j
public class WebSocket {
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    /**
     * 新建webSocket配置类
     * @return
     */
//    @Bean
//    public ServerEndpointExporter serverEndpointExporter() {
//        return new ServerEndpointExporter();
//    }
    /**
     * 建立连接
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSockets.add(this);
        log.info("【新建连接】,连接总数:{}", webSockets.size());
    }

    /**
     * 断开连接
     */
    @OnClose
    public void onClose(){
        webSockets.remove(this);
        log.info("【断开连接】,连接总数:{}", webSockets.size());
    }

    /**
     * 接收到信息
     * @param message
     */
    @OnMessage
    public void onMessage(String message){
        log.info("【收到】,客户端的信息:{},连接总数:{}", message, webSockets.size());
    }

    /**
     * 发送消息
     * @param message
     */
    public void sendMessage(String message){
        log.info("【广播发送】,信息:{},总连接数:{}", message, webSockets.size());
        for (WebSocket webSocket : webSockets) {
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.info("【广播发送】,信息异常:{}", e.fillInStackTrace());
            }
        }
    }

}
3.vue前端
this.$http
        .post("http://localhost:8989/pay/alipay", this.cart)
        .then((res) => {
          console.log(res)
          console.log(res.data)
          if (res.status === 200) {
            _this.text = res.data
            _this.dialogVisible = true;
            //使用websocket发送请求
            if ("WebSocket" in window) {
              //打开一个web socket
              var ws = new WebSocket("ws://localhost:8989/bindingRecord")
              ws.onopen = function () {
                ws.send("客户端向8989端口发送请求...")
              }
              ws.onmessage = function (evt) {
                var recevied_msg = evt.data
                console.log(recevied_msg)
                if (Boolean(recevied_msg)) {
                  _this.paySucc = true;
                  setTimeout(() => {
                    _this.dialogVisible = false;//支付弹窗关闭
                  }, 3 * 1000)
                }
                ws.close()
              }
              ws.onclose = function () {
                console.log("连接已经关闭")
              }
            } else {
              alert("您的浏览器不支持websocket!")
            }
          }
        }).catch((err) => {
        console.log(err)
      });

还有,中途碰到前端连接不上的问题,WebSocket connection to 'ws://localhost:8989/bindingRecord' failed。

如图所示,

查了很多博客,都是说前端代码的问题,但是实际上,很可能是后端他没有接收到人家的请求,没有响应。是后端代码写的有问题,我把依赖中scope那行加上之后(记得刷新maven),就没有这个错误了,具体原理我其实并不是很清楚。可参见这两篇博客,Tomcat 8 和网络套接字   DeploymentException

前端:

后端:

posted @ 2023-11-25 17:03  YuKiCheng  阅读(49)  评论(0)    收藏  举报  来源