73 lines
2.0 KiB
C#
73 lines
2.0 KiB
C#
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
|
||
|
||
|
||
}
|
||
}
|