c# - 从 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);
}
}
解决方案
推荐阅读
- python - 如何将文件复制到 Django Web 服务器的“文档根目录”
- python - 将 RGB 热图图像转换为灰度热图的正确方法
- javascript - 理解 JavaScript 中的 bind()
- sql - 如何在 FUNCTION 中使用 GROUP 函数(MAX)?
- video - 两个视频 - 一个与闪烁的 LED 同步;全部按 GPIO 按钮
- java - 服务和控制器之间打开多线程有什么区别?
- java - Java 8从对象列表创建地图的地图
- angular - 特定页面上的 Ionic 3 导航
- html - SVG:用封闭的矩形或 SVG 元素缩放文本?
- javascript - 使用css显示或隐藏表格中的元素,javascript每次都会将数据表滚动到顶部