ESP32的客户端端口也要指定
时间: 2023-10-02 18:04:26 浏览: 39
是的,当 ESP32 作为客户端连接 TCP 服务器时,需要指定客户端的本地端口号。可以使用 WiFiClient 类的 connect() 函数的第二个参数来指定本地端口号。下面是一个示例代码,可供参考:
```c++
#include <WiFi.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* host = "your_HOST";
const int port = 1234; // 服务器端口号
const int localPort = 1234; // 客户端本地端口号
void setup() {
Serial.begin(9600);
delay(10);
// 连接 Wi-Fi
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");
// 连接 TCP 服务器
WiFiClient client;
if (!client.connect(host, port, localPort)) {
Serial.println("Connection failed");
return;
}
// 发送数据
client.print("Hello, server!");
// 读取响应
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
// 断开连接
client.stop();
Serial.println("Done");
}
void loop() {
}
```
在上面的代码中,将 localPort 设置为客户端的本地端口号,然后将其传递给 connect() 函数的第三个参数。这样就可以指定客户端的本地端口号了。注意,需要将 host 替换为服务器的 IP 地址,port 替换为服务器的端口号。
相关推荐
![PDF](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)