当前位置:   article > 正文

Winform中使用Websocket4Net实现Websocket客户端并定时存储接收数据到SQLite中_websocket发送消息,并将消息存放到数据库

websocket发送消息,并将消息存放到数据库

场景

SpringBoot+Vue整合WebSocket实现前后端消息推送:

SpringBoot+Vue整合WebSocket实现前后端消息推送_websocket vue3.0 springboot 往客户端推送-CSDN博客

上面实现ws推送数据流程后,需要在windows上使用ws客户端定时记录收到的数据到文件中,这里

文件使用SQLite数据库进行存储。

Winform中操作Sqlite数据增删改查、程序启动时执行创建表初始化操作:

Winform中操作Sqlite数据增删改查、程序启动时执行创建表初始化操作_winform sqllite-CSDN博客

Sqlite的操作参考如上。

注:

博客:
霸道流氓气质_C#,架构之路,SpringBoot-CSDN博客

实现

1、引入WebSocket4Net依赖

使用Nuget搜索并安装WebSocket4Net

2、设计页面布局如下

3、websocket客户端实现

声明客户端对象

public static WebSocket4Net.WebSocket webSocket4NetClient = null;

ws连接按钮的点击事件中

  1.             try {
  2.                 var wsAddresss = textBox_ws_address.Text.Trim();
  3.                 webSocket4NetClient = new WebSocket4Net.WebSocket(wsAddresss);
  4.                 webSocket4NetClient.Opened += WebSocket4Net_Opened;
  5.                 webSocket4NetClient.Error += Websocket_Error;
  6.                 webSocket4NetClient.Closed += new EventHandler(Websocket_Closed);
  7.                 webSocket4NetClient.MessageReceived += WebSocket4Net_MessageReceived;
  8.                 webSocket4NetClient.Open();
  9.                 textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":ws开始连接");
  10.                 textBox_log.AppendText("\r\n");
  11.             } catch (Exception exception) {
  12.                 textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":ws连接异常:"+ exception.Message);
  13.                 textBox_log.AppendText("\r\n");
  14.             }

这里未添加对ws地址的校验,只关注中间ws相关的代码

  1.                 webSocket4NetClient = new WebSocket4Net.WebSocket(wsAddresss);
  2.                 webSocket4NetClient.Opened += WebSocket4Net_Opened;
  3.                 webSocket4NetClient.Error += Websocket_Error;
  4.                 webSocket4NetClient.Closed += new EventHandler(Websocket_Closed);
  5.                 webSocket4NetClient.MessageReceived += WebSocket4Net_MessageReceived;
  6.                 webSocket4NetClient.Open();

然后编写其各种事件的具体实现。

实现方法中具体逻辑根据业务进行确定。

建立连接事件实现

  1.         private void WebSocket4Net_Opened(object sender, EventArgs e)
  2.         {
  3.             //允许跨线程调用
  4.             Control.CheckForIllegalCrossThreadCalls = false;
  5.             textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":ws建立连接成功");
  6.             textBox_log.AppendText("\r\n");
  7.             //向服务端发送消息
  8.             //webSocket4NetClient.Send("Client准备发送数据!");
  9.         }

收到消息事件实现

  1.         private void WebSocket4Net_MessageReceived(object sender, MessageReceivedEventArgs e)
  2.         {
  3.             //允许跨线程调用
  4.             Control.CheckForIllegalCrossThreadCalls = false;
  5.             //textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":收到消息:");
  6.             //textBox_log.AppendText("\r\n");
  7.             receviceString = e.Message;
  8.         }

出错事件实现

  1.         private void Websocket_Error(object sender, EventArgs e)
  2.         {
  3.             //允许跨线程调用
  4.             Control.CheckForIllegalCrossThreadCalls = false;
  5.             textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":Websocket_Error:"+e);
  6.             textBox_log.AppendText("\r\n");
  7.         }

连接关闭事件实现

  1.         private void Websocket_Closed(object sender, EventArgs e)
  2.         {
  3.             //允许跨线程调用
  4.             Control.CheckForIllegalCrossThreadCalls = false;
  5.             textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":Websocket_Closed");
  6.             textBox_log.AppendText("\r\n");
  7.         }

ws连接关闭按钮点击实现

  1.         private void button_ws_disconnec_Click(object sender, EventArgs e)
  2.         {
  3.             webSocket4NetClient.Close();
  4.         }

4、定时存储实现

在上面收到消息时将数据赋值给变量

receviceString

声明变量

private string receviceString = String.Empty;

添加Timer定时器

Timer _timer = new Timer();

定时存储按钮点击事件实现

  1.         private void button_start_store_Click(object sender, EventArgs e)
  2.         {
  3.             if (webSocket4NetClient.State != WebSocket4Net.WebSocketState.Open && webSocket4NetClient.State != WebSocket4Net.WebSocketState.Connecting)
  4.             {
  5.                 textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":Websocket连接异常");
  6.                 textBox_log.AppendText("\r\n");
  7.             }
  8.             else {
  9.                 //清空数据库
  10.                 SQLiteDataReader reader = Global.Instance.sqlLiteHelper.ExecuteQuery("SELECT* FROM positions;");
  11.                 if (reader.HasRows)
  12.                 {
  13.                     while (reader.Read())
  14.                     {
  15.                         Global.Instance.sqlLiteHelper.ExecuteQuery("DELETE FROM positions WHERE timestamp = " + reader.GetString(reader.GetOrdinal("timestamp")) + ";");
  16.                     }
  17.                 }
  18.                 _timer.Interval = (int)numericUpDown_rate.Value;
  19.                 _timer.Tick += _timer_Tick;
  20.                 _timer.Start();
  21.                 textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":定时存储已经启动!!");
  22.                 textBox_log.AppendText("\r\n");
  23.             }
  24.         }

首先判断ws是否连接上,如果连接上则将库清空,然后获取设置的定时频率并启动定时器

定时器具体实现

  1.         private void _timer_Tick(object sender, EventArgs e) {
  2.             try
  3.             {
  4.                 if (webSocket4NetClient.State != WebSocket4Net.WebSocketState.Open && webSocket4NetClient.State != WebSocket4Net.WebSocketState.Connecting)
  5.                 {
  6.                     textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":Websocket连接异常");
  7.                     textBox_log.AppendText("\r\n");
  8.                 }
  9.                 else {
  10.                     if (!String.IsNullOrEmpty(receviceString))
  11.                     {
  12.                         //获取ws数据并存储进数据库
  13.                         TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  14.                         string timeSpan = Convert.ToInt64(ts.TotalSeconds).ToString();
  15.                         //插入数据
  16.                         Global.Instance.sqlLiteHelper.InsertValues("positions", new string[] { timeSpan, receviceString });
  17.                         receviceString = String.Empty;
  18.                     }
  19.                 }
  20.             }
  21.             catch (Exception exception)
  22.             {
  23.                 textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":定时存储执行异常:" + exception.Message);
  24.                 textBox_log.AppendText("\r\n");
  25.             }        
  26.         }

首页也要判断是否连接,然后判断receviceString是否为空,避免ws未传输数据,会定时存储空数据。

不为空则将时间和收到的数据存储进数据库。

停止定时存储按钮点击事件

  1.         private void button_stop_store_Click(object sender, EventArgs e)
  2.         {
  3.             //停止定时器
  4.             _timer.Tick -= _timer_Tick;
  5.             _timer.Stop();
  6.             textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":定时存储已经停止!!!");
  7.             textBox_log.AppendText("\r\n");
  8.             receviceString = String.Empty;
  9.         }

5、运行效果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/191244
推荐阅读
相关标签
  

闽ICP备14008679号