0

我有一个带有 ESP8266 和 Spring Boot 服务器的简单项目。我想通过 websocket 将数据从 ESP 发送到服务器。

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

Spring Boot 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\"}");
}

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

4

1 回答 1

0

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

const char* ws_baseurl = "/esp-websocket/"; // 不要忘记前导和尾随“/” !!!

在 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";
  }

然后您应该将套接字 url 修改为:

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

或禁用 sockJS 创建 stomp 客户端:

Stomp::StompClient stomper(webSocket, ws_host, ws_port, ws_baseurl, false);
于 2019-06-07T06:32:17.760 回答