| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- #include <WiFi.h>
- //网络配置
- const char* ssid = "cdjs_work";
- const char* password = "cdjs654321aA";
- //sockt服务器地址
- const char* host = "81.70.80.219";
- const uint16_t port = 49700;
- volatile uint16_t state = 0;
- WiFiClient client;
- // WIFI连接
- void netConnect(){
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.println("WIFI connection...");
- }
- Serial.println("WiFi connected IP:");
- Serial.println(WiFi.localIP());
- }
- //socekt 连接
- void soConnect(){
- // 判断是否有网
- if(WiFi.status() == WL_CONNECTED){
- //若未连接到服务端,则客户端进行连接。
- if(client.connected()){
- //增加状态
- if(state == 0){
- Serial.println("socket connected!");
- state = 1;
- }
- // 发送
- delay(2000);
- Serial.println("发送:test");
- client.println("test");
- }else{
- // 判断状态
- if(state == 1){
- Serial.println("socket restart connection...");
- state = 0;
- }
- // 连接服务器
- Serial.println("socket connection...");
- client.connect(host, port);
- delay(1000);
- }
- }else{
- // 重新连接网络
- netConnect();
- }
- }
- void setup() {
- // put your setup code here, to run once:
- Serial.begin(115200);
- netConnect();
- }
- void loop() {
- // put your main code here, to run repeatedly:
- soConnect();
- }
|