文章目录
- 前言
- Fleck
- 调试工具
- 初始化
- 简单使用
前言
最近接到了一个需求,需要网页实现上位机的功能。那就对数据传输的实时性要求很高。那就只能用WebSocket了。这里简单说一下我的WebSocket如何搭建
Fleck
C# WebSocket(Fleck) 客户端:html Winfrom
Fleck Github官网
我这里用的Fleck去做Websocket。如果有更好的Websocket包可以评论区说一下。
调试工具
这里推荐使用PostMan,自己
初始化
这样太简单了,我们需要对他进行简单封装一下
using Bogus;using ConsoleApp1.Models;using Fleck;using Models;using Newtonsoft.Json;using Newtonsoft.Json.Converters;using System;using System.Collections.Generic;using System.Linq;using System.Net.Sockets;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;using static System.Runtime.InteropServices.JavaScript.JSType;namespace ConsoleApp1.Services{public class OutPartail_PRPD_Service{public List<IWebSocketConnection> Connections { get; set; }public WebSocketServer WebSocketServer { get; set; }public OutPartail_PRPD_Service(){Connections = new List<IWebSocketConnection>();WebSocketServer = new WebSocketServer("ws://0.0.0.0:7081");WebSocketServer.Start(socket =>{socket.OnOpen = () =>{PrintMsg("客户端连接成功!");Connections.Add(socket);PrintMsg("当前客户端数量:" + Connections.ToList().Count);};socket.OnClose = () =>{PrintMsg("客户端已经关闭!");Connections.Remove(socket);PrintMsg("当前客户端数量:" + Connections.ToList().Count);};socket.OnError = (e) =>{PrintMsg("客户端运行遇到问题");PrintMsg(e.ToString());};//收到消息时socket.OnMessage = message =>{PrintMsg($"接收到[{socket.ConnectionInfo.Id}]信息:{message}");socket.Send(message);};});}//打印数据private void PrintMsg(string msg){Console.WriteLine($"{SocketName}:{msg}");}//向所有已连接的对象发送数据public void SendMsg(string msg){foreach (var item in Connections){item.Send(msg);}}}
简单使用
/// /// Sim卡切换/// /// public async Task ChangeSimNo(int index){int row = (index / 12);string col = Convert.ToInt32(index % 12).ToString("X1");var msg = $"AT+S{row}{col}";SimNo = -1;Send(msg);try{var res = await Recive(waitTime);ShowMsg(res);res = await Recive(waitTime);if (res.Contains("OK")){SimNo = index;ShowMsg($"Sim[{index}]卡切换成功!");}else{ShowMsg($"Sim[{index}]卡接受报文错误,应为OK!");}}catch (Exception ex){throw new Exception("等待OK超时");}}