从 ESP32 连接到部署到 Heroku 的 websocket 服务器时出现问题

时间:2021-01-28 18:00:18

标签: heroku websocket openssl esp32 pem

这是我拥有的 ESP32 代码。我使用

生成了一个 .pem 文件

openssl s_client -showcerts -connect hidden-thicket-03510.herokuapp.com:443

但我仍然无法使用 WiFisecureClient 连接到服务器。

你能告诉我我做错了什么吗?我的猜测是我在附加证书时做错了什么。

感谢您的帮助

#include <WiFiClientSecure.h>
#include <WebSocketClient.h>
#include <ArduinoJson.h> 
const char* ssid     = "##";
const char* password = "###";
 
char path[] = "/";
char host[] = "https://hidden-thicket-03510.herokuapp.com";
 
WebSocketClient webSocketClient;
WiFiClientSecure client;

const char* test_root_ca= \
  "-----BEGIN CERTIFICATE-----\n" \
  "MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs\n" \
  "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \
  "d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j\n" \
  "ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL\n" \
  "MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3\n" \
  "LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug\n" \
  "RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm\n" \
  "+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW\n" \
  "PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM\n" \
  "xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB\n" \
  "Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3\n" \
  "hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg\n" \
  "EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF\n" \
  "MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA\n" \
  "FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec\n" \
  "nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z\n" \
  "eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF\n" \
  "hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2\n" \
  "Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe\n" \
  "vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep\n" \
  "+OkuE6N36B9K\n" \
  "-----END CERTIFICATE-----\n";

int timer=0;

void connnect() {
  if (client.connect(host,443)) {
    Serial.println("Connected");
  } else {
    Serial.println("Connection failed.");
  }
 
  webSocketClient.path = path;
  webSocketClient.host = host;
  if (webSocketClient.handshake(client)) {
    Serial.println("Handshake successful");
  } else {
    Serial.println("Handshake failed.");
  }
}

void setup() {
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
 
  delay(5000);
  client.setCACert(test_root_ca);
  
  connnect();

  if (client.connected()) {
    webSocketClient.sendData("Info to be echoed back");
  }
}
 
void loop() {
  String data;
  
  if (client.connected()) {
    webSocketClient.getData(data);
    Serial.println(data);
    int data_len = data.length() + 1; 
    char char_array[data_len];
    data.toCharArray(char_array, data_len);
    StaticJsonDocument<1200> doc;

    const char* a=doc["message"];
    
    if (data_len > 1) {
      Serial.print("Received data: ");
      Serial.println(a);
    }
  } else {
    Serial.println("Client disconnected.");
    connnect();
  }
 
  delay(3000);
}

如果有帮助的话,这是在 Heroku 上运行的服务器代码:

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
let port =process.env.PORT || 5000;
server.listen(port, function() {
    console.log((new Date()) + ' Server is listening on port 5000');
});

wsServer = new WebSocketServer({
    httpServer: server
});
const clients={}
wsServer.on('request', request=> { 
    var connection = request.accept(null, request.origin);
    console.log((new Date()) + ' Connection accepted.');
    
    const clientId=guid();
    clients[clientId]={
        "connection":connection
    };

    // connection.sendUTF("JSON.stringify(payload)")
    connection.on('open',()=>{console.log("opened")})

    connection.on('message', message => {
        console.log(message);
        var a=JSON.stringify({'message':'sdaed'})
        connection.send(a)
        
    });

    connection.on('close', (reasonCode, description) =>{
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });

    const payload={
        "method":"connect",
        "clientId":clientId
    }
    
});

const guid=()=> {
    const s4=()=> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);     
    return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;
  }

串行输出是,

Connected
Waiting...
Waiting...
Waiting...
Handshake failed.
Client disconnected.
Connected
Waiting...
Waiting...
Waiting...
Handshake failed.
Client disconnected.
Connected
Waiting...
Waiting...
Waiting...
Waiting...
Waiting...
Handshake failed.

0 个答案:

没有答案