首页 > 解决方案 > 从 ESP32 到 Winform 的 Websocket 连接

问题描述

我正在将 I2S 数据从 ESP32 服务器发送到 Winform 客户端。即使客户端已连接,串行监视器也不会显示它已连接。也没有数据从服务器传输到客户端。但是一旦 Winform 关闭,串口监视器就会显示“Client Disconnected”。这可能是什么原因?

服务器端代码

#include <driver/i2s.h>
#include <ArduinoWebsockets.h>

const i2s_port_t I2S_PORT = I2S_NUM_0;
//-----------------------------------------------
const char* ssid = "xxx";
const char* password = "xxx";

//WiFiServer server (80);
using namespace websockets;
WebsocketsServer server;

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

  Serial.println("Configuring I2S...");
  esp_err_t err;

  // The I2S configuration 
 
  // The pin config as per the setup
  
 // Configuring the I2S driver and pins.
    }
  Serial.println("I2S driver installed.");

  WiFi.begin(ssid, password);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  while(WiFi.status() != WL_CONNECTED)
  {
    Serial.print("."); delay(500);  
  }
  WiFi.mode(WIFI_STA);
  Serial.print("WiFi connected with IP address: ");
  Serial.println(WiFi.localIP());
  
  server.listen(81);
}

void loop() {
  WebsocketsClient client = server.accept();
  
  
   if(client.available())
   {
    WebsocketsMessage msg = client.readBlocking();
    
    Serial.println("Client Connected");
    Serial.println(msg.data());

    int32_t sample = 0;
  int bytes_read = i2s_pop_sample(I2S_PORT, (char *)&sample, portMAX_DELAY); // no timeout
  if (bytes_read > 0) {
    String sampleString = String(sample);
    client.send(sampleString);
    Serial.println(sampleString);
  }
}
    Serial.println("Client Disconnected");
   }

客户端代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
       
        private void Form1_Load(object sender, EventArgs e)
        {
            client = new SimpleTcpClient();
            client.StringEncoder = Encoding.UTF8;
            client.DataReceived += Client_DataReceived;

        }

        private void Client_DataReceived(object sender, SimpleTCP.Message e)
        {
            textstatus.Invoke((MethodInvoker)delegate ()
            {
                textstatus.Text += e.MessageString;
               
            });
        }

        SimpleTcpClient client;

        private void btnconnect_Click(object sender, EventArgs e)
        {
            client.Connect(texthost.Text, Convert.ToInt32(textport.Text));
            btnconnect.Enabled = false;
        }

        private void btnsend_Click(object sender, EventArgs e)
        {
            //client.WriteLineAndGetReply(textmessage.Text,TimeSpan.FromSeconds(0));
            client.WriteLine(textmessage.Text);

        }
    }

标签: c#winformsesp32

解决方案


推荐阅读