Fleck是一个开源的使用C#封装的WebSocket服务端工具库。
Github源码:https://github.com/statianzo/Fleck
微软官方在.net框架里也提供了方法:https://docs.microsoft.com/en-us/dotnet/api/system.net.websockets.websocket?redirectedfrom=MSDN&view=netframework-4.5#remarks
一、服务端搭建
这里选择在.net core 2.1框架下新建了一个控制台程序
在项目里使用NuGet引入Fleck包
其它方式也可以,最终引入项目里都是Fleck.dll
二、服务端实例
Github上的简单例子:
简单实例:
using System;
using System.Collections.Generic;
using System.Linq;
using Fleck;
namespace ConsoleApp1
{
class Program
{
static voidMain(string[] args)
{
socketTest();
}
Public static voidsocketTest()
{
//管理Socket
var allSockets = newList();
//配置地址
var server = newWebSocketServer("ws://127.168.0.100:50000");
//出错后进行重启
server.RestartAfterListenError = true;
//开始监听
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("bili: " +message));
};
});
var input =Console.ReadLine();
foreach (varsocket in allSockets.ToList())
{
socket.Send(input);
}
input =Console.ReadLine();
}
}
}
三、客户端测试实例(网上copy)
websocket client
var start = function () {
var inc = document.getElementById('incomming');
var wsImpl = window.WebSocket || window.MozWebSocket;
var form = document.getElementById('sendForm');
var input = document.getElementById('sendText');
inc.innerHTML += "connecting to server ..
";
// create a new websocket and connect
window.ws = new wsImpl('ws://127.168.0.100:50000‘’);
// when data is comming from the server, this metod is called
ws.onmessage = function (evt) {
inc.innerHTML += evt.data + '
';
};
// when the connection is established, this method is called
ws.onopen = function () {
inc.innerHTML += '.. connection open
';
};
// when the connection is closed, this method is called
ws.onclose = function () {
inc.innerHTML += '.. connection closed
';
}
form.addEventListener('submit', function (e) {
e.preventDefault();
var val = input.value;
ws.send(val);
input.value = "";
});
}
window.onload = start;
浏览器打开网页就可以测试了。