You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
2.5 KiB
71 lines
2.5 KiB
using BBWY.Common.Models;
|
|
using Fleck;
|
|
using Newtonsoft.Json.Linq;
|
|
using System;
|
|
using System.Collections.Concurrent;
|
|
|
|
namespace BBWY.WebSocket.Server.Helpers
|
|
{
|
|
public class WSHelper : IDenpendency
|
|
{
|
|
private ConcurrentDictionary<string, IWebSocketConnection> bbwySocketPool;
|
|
|
|
private WebSocketServer wsServer;
|
|
|
|
public WSHelper()
|
|
{
|
|
|
|
}
|
|
|
|
public void Listen()
|
|
{
|
|
wsServer = new WebSocketServer("ws://127.0.0.1:35192");
|
|
bbwySocketPool = new ConcurrentDictionary<string, IWebSocketConnection>();
|
|
|
|
//开启监听
|
|
wsServer.Start(socket =>
|
|
{
|
|
//注册客户端连接建立事件
|
|
socket.OnOpen = () =>
|
|
{
|
|
Console.WriteLine("建立连接");
|
|
if (!string.IsNullOrEmpty(socket.ConnectionInfo.Path) && socket.ConnectionInfo.Path.Contains("bbwy"))
|
|
{
|
|
var key = socket.ConnectionInfo.Path.Substring(socket.ConnectionInfo.Path.LastIndexOf("/") + 1);
|
|
bbwySocketPool.TryRemove(key, out _);
|
|
bbwySocketPool.TryAdd(key, socket); //将bbwy当前客户端连接对象放入连接池中
|
|
}
|
|
};
|
|
//注册客户端连接关闭事件
|
|
socket.OnClose = () =>
|
|
{
|
|
if (!string.IsNullOrEmpty(socket.ConnectionInfo.Path) && socket.ConnectionInfo.Path.Contains("bbwy"))
|
|
{
|
|
var key = socket.ConnectionInfo.Path.Substring(socket.ConnectionInfo.Path.LastIndexOf("/") + 1);
|
|
bbwySocketPool.TryRemove(key, out _);
|
|
}
|
|
};
|
|
//注册客户端发送信息事件
|
|
socket.OnMessage = message =>
|
|
{
|
|
Console.WriteLine($"收到webSocket消息:{message}");
|
|
socket.Close();
|
|
|
|
try
|
|
{
|
|
var j = JObject.Parse(message);
|
|
if (!string.IsNullOrEmpty(j.Value<string>("user")))
|
|
{
|
|
if (bbwySocketPool.TryGetValue(j.Value<string>("user"), out IWebSocketConnection bbwySocket))
|
|
{
|
|
_ = bbwySocket.Send(message);
|
|
}
|
|
}
|
|
}
|
|
catch { }
|
|
};
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
|