ESP32_socket.ino 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <WiFi.h>
  2. //网络配置
  3. const char* ssid = "cdjs_work";
  4. const char* password = "cdjs654321aA";
  5. //sockt服务器地址
  6. const char* host = "81.70.80.219";
  7. const uint16_t port = 49700;
  8. volatile uint16_t state = 0;
  9. WiFiClient client;
  10. // WIFI连接
  11. void netConnect(){
  12. WiFi.mode(WIFI_STA);
  13. WiFi.begin(ssid, password);
  14. while (WiFi.status() != WL_CONNECTED) {
  15. delay(500);
  16. Serial.println("WIFI connection...");
  17. }
  18. Serial.println("WiFi connected IP:");
  19. Serial.println(WiFi.localIP());
  20. }
  21. //socekt 连接
  22. void soConnect(){
  23. // 判断是否有网
  24. if(WiFi.status() == WL_CONNECTED){
  25. //若未连接到服务端,则客户端进行连接。
  26. if(client.connected()){
  27. //增加状态
  28. if(state == 0){
  29. Serial.println("socket connected!");
  30. state = 1;
  31. }
  32. // 发送
  33. delay(2000);
  34. Serial.println("发送:test");
  35. client.println("test");
  36. }else{
  37. // 判断状态
  38. if(state == 1){
  39. Serial.println("socket restart connection...");
  40. state = 0;
  41. }
  42. // 连接服务器
  43. Serial.println("socket connection...");
  44. client.connect(host, port);
  45. delay(1000);
  46. }
  47. }else{
  48. // 重新连接网络
  49. netConnect();
  50. }
  51. }
  52. void setup() {
  53. // put your setup code here, to run once:
  54. Serial.begin(115200);
  55. netConnect();
  56. }
  57. void loop() {
  58. // put your main code here, to run repeatedly:
  59. soConnect();
  60. }