前言
最近接到了一个需求,需要网页实现上位机的功能。那就对数据传输的实时性要求很高。那就只能用WebSocket了。这里简单说一下我的WebSocket如何搭建
Fleck
我这里用的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($"{msg}");
}
//向所有已连接的对象发送数据
public void SendMsg(string msg)
{
foreach (var item in Connections)
{
item.Send(msg);
}
}
}