之前 使用 http库 做了一个比较骚的事情
就是esp32 http 轮询获取redis中的数据 做解析 这么做虽然可以实现我需要的功能
但是损耗太大了 因为要频繁发送请求

最好的方法是 使用websocket 由后端主动推送

这边 后端我是用Netty
esp32 使用到一个库叫 ArduinoWebsockets

代码比较简单


#include <ArduinoWebsockets.h>
#include <WiFi.h>

const char* ssid = "wifi"; //Enter SSID
const char* password = "password"; //Enter Password
const char* websockets_server_host = "192.168.31.120"; //Enter server adress
const uint16_t websockets_server_port = 8082; // Enter server port

using namespace websockets;

void onMessageCallback(WebsocketsMessage message) {
    Serial.print("Got Message: ");
    Serial.println(message.data());
}

void onEventsCallback(WebsocketsEvent event, String data) {
    if(event == WebsocketsEvent::ConnectionOpened) {
        Serial.println("Connnection Opened");
    } else if(event == WebsocketsEvent::ConnectionClosed) {
        Serial.println("Connnection Closed");
    } else if(event == WebsocketsEvent::GotPing) {
        Serial.println("Got a Ping!");
    } else if(event == WebsocketsEvent::GotPong) {
        Serial.println("Got a Pong!");
    }
}

WebsocketsClient client;
void setup() {
    Serial.begin(115200);
    // Connect to wifi
    WiFi.begin(ssid, password);

    // Wait some time to connect to wifi
    for(int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) {
        Serial.print(".");
        delay(1000);
    }

    // run callback when messages are received
    client.onMessage(onMessageCallback);
    
    // run callback when events are occuring
    client.onEvent(onEventsCallback);

    // Connect to server
    client.connect(websockets_server_host, websockets_server_port, "/ws?userId=2");

    // Send a message
    // client.send("Hello Server");

    // Send a ping
    // client.ping();
}

void loop() {
    client.poll();
}
最后修改:2024 年 03 月 31 日
如果觉得我的文章对你有用,请随意赞赏