C# 实现WebSocket通信
C# websocket本实例可通过web网页端进行测试,下面直接上代码
首先要在NuGet导入“Fleck”包,需 .NET Framework 4.5及以上
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Fleck.Samples.ConsoleApp
{
class Server
{
static void Main()
{
FleckLog.Level = LogLevel.Debug;
var allSockets = new List();
var server = new WebSocketServer(“ws://10.10.10.99:50000”);
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));
};
});
var input = Console.ReadLine();
while (input != “exit”)
{
foreach (var socket in allSockets.ToList())
{
socket.Send(input);
}
input = Console.ReadLine();
}
}
}
}
接下来就是测试阶段,首先运行窗体程序
测试方法:打开浏览器,F12进入调试模式,在Console中输入测试代码。(我使用的是谷歌浏览器
ws = new WebSocket(“ws://10.10.10.99:50001”);
ws.onopen = function() {
ws.send(‘websocekt测试’);
};
ws.onmessage = function(e) {
alert(“收到服务端的消息:” + e.data);
};
输入完毕后按回车执行,这时就可以在命令行中看到传过来的数据了