ESP8266 上的 Websocket 客户端不向 spring-boot 服务器发送数据

Websocket client on the ESP8266 doesn't send data to spring-boot server

我有一个使用 ESP8266 和 spring 引导服务器的简单项目。我想通过 websocket 将数据从 ESP 发送到服务器。

在 ESP 上,我正在使用这个库来创建 Stomp 客户端:https://github.com/ukmaker/StompClient

Spring 启动 ws 配置:

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.setApplicationDestinationPrefixes("/esp");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*").withSockJS();
    }

WS 控制器:

    @MessageMapping("/sensors")
    @CrossOrigin("*")
    public WsModel resendData(WsModel wsModel) {
        return wsModel;
    }

ESP8266:

#include "ESP8266WiFi.h"
#include <WebSocketsClient.h>
#include "StompClient.h"

const char* wlan_ssid = "******";
const char* wlan_password = "******";

const char* ws_host = "localhost";
const int ws_port = 9091;
const char* ws_baseurl = "/gs-guide-websocket"; 

WebSocketsClient  webSocket;

Stomp::StompClient stomper(webSocket, ws_host, ws_port, ws_baseurl, true);

void setup(void)
{ 
  Serial.begin(115200);
  WiFi.begin(wlan_ssid, wlan_password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  ...some code

  stomper.begin();
}

void loop() {
  webSocket.loop();
  stomper.sendMessage("/esp/sensors", "{\"name\":\"test\"}");
}

我没有收到任何错误消息。它只是不发送任何数据。

查看 StompClient 库示例 SpringStompButtons.ino,我们可以看到评论:

const char* ws_baseurl = "/esp-websocket/"; // don't forget leading and trailing "/" !!!

在 sockJs 实现的文件 StompClient.h 中有:

  if (_sockjs) {
    socketUrl += random(0, 999);
    socketUrl += "/";
    socketUrl += random(0, 999999); // should be a random string, but this works (see )
    socketUrl += "/websocket";
  }

那你应该修改socket url 为:

const char* ws_baseurl = "/gs-guide-websocket/"; 

或禁用 sockJS 创建 stomp 客户端:

Stomp::StompClient stomper(webSocket, ws_host, ws_port, ws_baseurl, false);