C# WebSocket服务端
引用nuget包Fleck
IDictionary<string, IWebSocketConnection> SocketList = new Dictionary<string, IWebSocketConnection>();
private void startSockeListener()
{
WebSocketServer server = new WebSocketServer("ws://127.0.0.1:30007");//监听本机
//出错后进行重启
server.RestartAfterListenError = true;
//开始监听
server.Start(socket =>
{
socket.OnOpen = () => //连接建立事件
{
//客户端url
string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
SocketList.Add(clientUrl, socket);
socket.Send("hello");
};
socket.OnClose = () => //连接关闭事件
{
string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
//如果存在这个客户端,那么对这个socket进行移除
if (SocketList.ContainsKey(clientUrl))
{
//if (SocketList[clientUrl] != null)
//{
// SocketList[clientUrl].Close();
//}
SocketList.Remove(clientUrl);
}
};
socket.OnMessage = message => //接受客户端网页消息事件
{
Console.WriteLine(message);
};
});
}
//向客户端发送消息
private void SendMessage(string msg)
{
foreach (var item in SocketList.Values)
{
if (item.IsAvailable == true)
{
item.Send(msg);
}
}
}
//关闭与所有客户端的连接
private void CloseSocket()
{
foreach (var item in SocketList.Values)
{
if (item != null)
{
item.Close();
}
}
}