73 lines
2.0 KiB
C#
Raw Normal View History

2025-07-04 09:50:02 +08:00
using Fleck;
using MyCode.Project.Domain.Config;
using MyCode.Project.Infrastructure.Enumeration;
using MyCode.Project.Services.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication;
using MyCode.Project.Infrastructure.Cache;
using log4net;
using MyCode.Project.Infrastructure.Common;
namespace MyCode.Project.Services.Implementation
{
/// <summary>
/// WebSocket服务
/// </summary>
public class WebSocketService : ServiceBase, IWebSocketService
{
#region
private readonly WebSocketBLL _webSocketBLL;
public WebSocketService(WebSocketBLL webSocketBLL)
{
_webSocketBLL = webSocketBLL;
}
#endregion
#region Init()
/// <summary>
/// 初始化
/// </summary>
public void Init()
{
//FleckLog.Level = LogLevel.;
//FleckLog.Error("FleckErrorTest");
var server = new WebSocketServer(SystemConfig.WebSocketUrl);
//如果有错误发生,自动重启
server.RestartAfterListenError = true;
//不要有延迟
server.ListenerSocket.NoDelay = true;
server.Start(socket =>
{
//打开连接事件
socket.OnOpen = () => { _webSocketBLL.OnOpenEvent(socket); };
//关闭连接事件
socket.OnClose = () => { _webSocketBLL.OnCloseEvent(socket); };
//客户端发送消息过来
socket.OnMessage = message =>
{
Console.WriteLine($"{DateTime.Now}OnMessage{message}");
if (message == "ping") { socket.Send("pong"); }
};
socket.OnError = exception => { _webSocketBLL.OnError(exception, socket); };
});
}
#endregion
}
}