-
Notifications
You must be signed in to change notification settings - Fork 30
/
SoraWebsocketClient.cs
190 lines (171 loc) · 8.41 KB
/
SoraWebsocketClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
using System;
using System.Net.WebSockets;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Sora.Exceptions;
using Sora.OnebotInterface;
using Sora.OnebotModel;
using Websocket.Client;
using YukariToolBox.FormatLog;
namespace Sora.Net
{
/// <summary>
/// Sora正向WS链接客户端
/// </summary>
public class SoraWebsocketClient
{
#region 属性
/// <summary>
/// 服务器配置类
/// </summary>
private ClientConfig Config { get; set; }
/// <summary>
/// WS服务器
/// </summary>
private WebsocketClient Client { get; set; }
/// <summary>
/// 心跳包检查计时器
/// </summary>
private Timer HeartBeatTimer { get; set; }
/// <summary>
/// 事件接口
/// </summary>
public EventInterface Event { get; }
/// <summary>
/// 服务器连接管理器
/// </summary>
public ConnectionManager ConnManager { get; }
#endregion
#region 私有字段
/// <summary>
/// 客户端已准备启动标识
/// </summary>
private readonly bool clientReady;
internal readonly Guid clientId = Guid.NewGuid();
#endregion
#region 构造方法
/// <summary>
/// 创建一个正向WS客户端
/// </summary>
/// <param name="config">服务器配置</param>
/// <param name="crashAction">发生未处理异常时的回调</param>
public SoraWebsocketClient(ClientConfig config, Action<Exception> crashAction = null)
{
Log.Info("Sora", $"Sora 框架版本:{Assembly.GetExecutingAssembly().GetName().Version}");
Log.Debug("Sora", "开发交流群:1081190562");
//检查端口占用
if (!NetUtils.IsPortInUse(config.Port))
{
Log.Fatal("Sora", $"端口{config.Port}没有任何服务器在运行");
Log.Warning("Sora", "将在5s后自动退出");
Thread.Sleep(5000);
Environment.Exit(0);
}
clientReady = false;
Log.Info("Sora", "Sora WebSocket客户端初始化...");
Log.Debug("System", Environment.OSVersion);
//初始化连接管理器
ConnManager = new ConnectionManager(config);
//检查参数
if (config == null) throw new ArgumentNullException(nameof(config));
if (config.Port == 0 || config.Port > 65535)
throw new ArgumentOutOfRangeException(nameof(config.Port), "Port out of range");
//初始化连接管理器
ConnManager = new ConnectionManager(config);
this.Config = config;
//API超时
ReactiveApiManager.TimeOut = config.ApiTimeOut;
//实例化事件接口
this.Event = new EventInterface(config.EnableSoraCommandManager);
//构建Client配置
var factory = new Func<ClientWebSocket>(() =>
{
var clientWebSocket = new ClientWebSocket();
clientWebSocket.Options.SetRequestHeader("Authorization",
$"Bearer {config.AccessToken}");
return clientWebSocket;
});
this.Client = new WebsocketClient(new Uri($"ws://{config.Host}:{config.Port}"), factory);
//全局异常事件
AppDomain.CurrentDomain.UnhandledException += (_, args) =>
{
if (crashAction == null)
NetUtils.FriendlyException(args);
else
crashAction(args.ExceptionObject as Exception);
};
clientReady = true;
}
#endregion
/// <summary>
/// 启动客户端并自动连接服务器
/// </summary>
public async ValueTask StartClient()
{
if (!clientReady) return;
//检查是否已有服务器被启动
if (NetUtils.serviceExitis) throw new SoraClientIsRuningException();
//消息接收订阅
Client.MessageReceived.Subscribe(msg => Task.Run(() =>
{
this.Event
.Adapter(JObject.Parse(msg.Text), clientId);
}));
Client.DisconnectionHappened.Subscribe(info => Task.Run(() =>
{
ConnectionManager.GetLoginUid(clientId,
out var uid);
//移除原连接信息
if (ConnectionManager.ConnectionExitis(clientId)
)
ConnManager.CloseConnection("Universal",
uid.ToString(), clientId);
Log.Info("Sora", "服务器连接被关闭");
if (info.Exception != null)
Log.Error("Sora",
Log
.ErrorLogBuilder(info
.Exception));
}));
Client.ReconnectionHappened.Subscribe(info => Task.Run(() =>
{
if (info.Type == ReconnectionType.Initial)
return;
Log.Info("Sora", $"服务器已自动重连");
ConnManager.OpenConnection("Universal", "0",
Client, clientId);
}));
await Client.Start();
if (!Client.IsRunning || !Client.IsStarted)
{
throw new WebSocketClientException("WebSocket client is not running");
}
ConnManager.OpenConnection("Universal", "0", Client, clientId);
Log.Info("Sora", "Sora WebSocket客户端正在运行并已连接至onebot服务器");
//启动心跳包超时检查计时器
this.HeartBeatTimer = new Timer(ConnManager.HeartBeatCheck, null,
new TimeSpan(0, 0, 0, (int) Config.HeartBeatTimeOut, 0),
new TimeSpan(0, 0, 0, (int) Config.HeartBeatTimeOut, 0));
NetUtils.serviceExitis = true;
await Task.Delay(-1);
}
/// <summary>
/// GC析构函数
/// </summary>
~SoraWebsocketClient()
{
Dispose();
}
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
Client.Dispose();
GC.SuppressFinalize(this);
ReactiveApiManager.ClearApiReqList();
}
}
}