2025-07-04 09:50:02 +08:00

73 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}
}