ESP8266 Web套接字与特定源端口的连接

时间:2019-01-11 17:06:21

标签: websocket arduino iot esp8266 arduino-esp8266

我正在使用ESP8266开发Web套接字连接。我有一个用Nodejs在192.168.20.21:8080上开发的websocket服务器(非常简单),并且websocket客户端是ESP8266。 这样我就可以通过websocket从ESP8266向服务器发送消息。

可以定义消息的源端口吗? ESP8266可以管理多少个websocket连接?

#include <ESP8266WiFi.h>
#include <WebSocketClient.h>

const char* ssid     = "test";
const char* password = "test";
char path[] = "/";
char host[] = "192.168.20.21";

WebSocketClient webSocketClient;

// Use WiFiClient class to create TCP connections
WiFiClient client;
WiFiClient client2;

void setup() {
  Serial.begin(115200);
  delay(10);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  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);


  // Connect to the websocket server
  if (client.connect("192.168.20.21", 8080)) {
    Serial.println("Connected");
  } else {
    Serial.println("Connection failed.");
    while(1) {
      // Hang on failure
    }
  }

  // Handshake with the server
  webSocketClient.path = path;
  webSocketClient.host = host;
  if (webSocketClient.handshake(client)) {
    Serial.println("Handshake successful");
  } else {
    Serial.println("Handshake failed.");
    while(1) {
      // Hang on failure
    }  
  }

}


void loop() {
  String data;
  if (client.connected()) {

    // capture the value of analog 1, send it along

    data = String("Connessione 1");
  webSocketClient2.sendData(data);

  } else {
    Serial.println("Client disconnected.");
    while (1) {
  // Hang on disconnect.
    }
  }
  // wait to fully let the client disconnect
  delay(3000);

}

我的想法是定义ESP8266的IP:PORT源。例如192.168.20.30:84(192.168.20.30是ESP的IP地址)。

非常感谢

0 个答案:

没有答案