C# websocket类库Fleck学习
前端:可以用这个篇介绍的代码,详解JS WebSocket断开原因和心跳机制
后端:winform程序编译成控制台程序
using Fleck;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
StartWebSocket();
}
static List<IWebSocketConnection> allSockets = new List<IWebSocketConnection>();
private static void StartWebSocket()
{
FleckLog.Level = LogLevel.Debug;
var server = new WebSocketServer("ws://0.0.0.0:7181");
server.Start(socket =>
{
socket.OnOpen = () =>
{
Console.WriteLine("Open!");
allSockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine("Close!");
allSockets.Remove(socket);
};
socket.OnMessage = message =>
{
Console.WriteLine(message);
allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
};
});
}
/// <summary>
/// 发消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
foreach (var socket in allSockets.ToList())
{
if (socket.IsAvailable == true)
{
socket.Send(textBox2.Text);
}
}
textBox2.Text = "";
}
/// <summary>
/// 关闭所有连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//关闭与客户端的所有的连接
foreach (var item in allSockets)
{
if (item != null)
{
item.Close();
}
}
}
}
- WebSocket和SocketIO、SignalR总结:WebSocket是H5提出的规范,仍然有浏览器不支持。SocketIO将WebSocket、AJAX和其它的通信方式全部封装成了统一的通信接口。WebSocket是SocketIO的一个子集。SignalR是微软出品的SocketIO。