AbstractWsClient.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. using NTMiner.User;
  2. using System;
  3. using System.Reflection;
  4. using System.Text;
  5. using WebSocketSharp;
  6. namespace NTMiner.Ws {
  7. public abstract class AbstractWsClient : IWsClient {
  8. private int _continueCount = 0;
  9. private int _failConnCount = 0;
  10. private string _closeReason = string.Empty;
  11. private string _closeCode = string.Empty;
  12. private WebSocket _ws = null;
  13. private bool _isOuterUserEnabled;
  14. // 用来判断用户是否改变了outerUserId,如果改变了则需要关闭连接使用新用户重新连接,该值根据_appType的不同而不同,
  15. // MinerClient时_outerUserId是来自注册表的OuterUserId,MinerStudio时_outerUserId是RpcRoot.RpcUser.LoginName
  16. private string _outerUserId = string.Empty;
  17. private AESPassword _aesPassword;
  18. #region ctor
  19. private readonly NTMinerAppType _appType;
  20. public AbstractWsClient(NTMinerAppType appType) {
  21. _appType = appType;
  22. VirtualRoot.AddEventPath<Per1SecondEvent>("重试Ws连接的秒表倒计时", LogEnum.None, action: message => {
  23. if (NextTrySecondsDelay > 0) {
  24. NextTrySecondsDelay--;
  25. }
  26. }, typeof(VirtualRoot));
  27. VirtualRoot.AddEventPath<Per10SecondEvent>("周期检查Ws连接", LogEnum.None,
  28. action: message => {
  29. NTMinerRegistry.SetDaemonActiveOn(DateTime.Now);
  30. if (_continueCount >= _failConnCount) {
  31. _continueCount = 0;
  32. OpenOrCloseWs();
  33. }
  34. else {
  35. _continueCount++;
  36. }
  37. }, typeof(VirtualRoot));
  38. VirtualRoot.AddEventPath<Per20SecondEvent>("周期Ws Ping", LogEnum.None, action: message => {
  39. try {
  40. if (_ws != null && _ws.ReadyState == WebSocketState.Open) {
  41. // 或者_ws.IsAlive,因为_ws.IsAlive内部也是一个Ping,所以用Ping从而显式化这里有个网络请求
  42. if (!_ws.Ping()) {
  43. _ws.CloseAsync(CloseStatusCode.Away);
  44. }
  45. }
  46. }
  47. catch (Exception e) {
  48. Logger.ErrorDebugLine(e);
  49. }
  50. }, typeof(VirtualRoot));
  51. VirtualRoot.AddEventPath<AppExitEvent>("退出程序时关闭Ws连接", LogEnum.DevConsole, action: message => {
  52. _ws?.CloseAsync(CloseStatusCode.Normal, "客户端程序退出");
  53. }, this.GetType());
  54. OpenOrCloseWs();
  55. }
  56. #endregion
  57. public bool IsOpen {
  58. get {
  59. if (!_isOuterUserEnabled) {
  60. return false;
  61. }
  62. return _ws != null && _ws.ReadyState == WebSocketState.Open;
  63. }
  64. }
  65. public DateTime LastTryOn { get; private set; } = DateTime.MinValue;
  66. public int NextTrySecondsDelay { get; private set; } = -1;
  67. protected abstract bool TryGetHandler(string messageType, out Action<Action<WsMessage>, WsMessage> handler);
  68. protected abstract void UpdateWsStateAsync(string description, bool toOut);
  69. #region SendAsync
  70. public void SendAsync(WsMessage message) {
  71. if (!IsOpen) {
  72. return;
  73. }
  74. switch (_appType) {
  75. case NTMinerAppType.MinerClient:
  76. _ws.SendAsync(message.ToBytes(), null);
  77. break;
  78. case NTMinerAppType.MinerStudio:
  79. _ws.SendAsync(message.SignToBytes(RpcRoot.RpcUser.Password), null);
  80. break;
  81. default:
  82. break;
  83. }
  84. }
  85. #endregion
  86. #region StartOrCloseWs
  87. public void OpenOrCloseWs(bool isResetFailCount = false) {
  88. try {
  89. if (isResetFailCount) {
  90. ResetFailCount();
  91. }
  92. switch (_appType) {
  93. case NTMinerAppType.MinerClient:
  94. _isOuterUserEnabled = NTMinerRegistry.GetIsOuterUserEnabled();
  95. break;
  96. case NTMinerAppType.MinerStudio:
  97. _isOuterUserEnabled = true;
  98. break;
  99. default:
  100. _isOuterUserEnabled = false;
  101. break;
  102. }
  103. string outerUserId;
  104. switch (_appType) {
  105. case NTMinerAppType.MinerClient:
  106. outerUserId = NTMinerRegistry.GetOuterUserId();
  107. break;
  108. case NTMinerAppType.MinerStudio:
  109. outerUserId = RpcRoot.RpcUser.LoginName;
  110. break;
  111. default:
  112. outerUserId = string.Empty;
  113. break;
  114. }
  115. if (!_isOuterUserEnabled) {
  116. ResetFailCount();
  117. if (_ws != null && _ws.ReadyState == WebSocketState.Open) {
  118. _ws.CloseAsync(CloseStatusCode.Normal, "外网群控已禁用");
  119. }
  120. return;
  121. }
  122. if (string.IsNullOrEmpty(outerUserId)) {
  123. ResetFailCount();
  124. _ws?.CloseAsync(CloseStatusCode.Normal, "未填写用户");
  125. return;
  126. }
  127. bool isUserIdChanged = _outerUserId != outerUserId;
  128. if (isUserIdChanged) {
  129. _outerUserId = outerUserId;
  130. }
  131. // 1,进程启动后第一次连接时
  132. if (_ws == null) {
  133. NewWebSocket(webSocket => _ws = webSocket);
  134. }
  135. else if (isUserIdChanged) {
  136. ResetFailCount();
  137. if (_ws.ReadyState == WebSocketState.Open) {
  138. // 因为旧的用户名密码成连接过且用户名或密码变更了,那么关闭连接即可,无需立即再次连接因为一定连接不成功因为用户名密码不再正确。
  139. string why = string.Empty;
  140. if (isUserIdChanged) {
  141. why = ",因为用户变更";
  142. }
  143. _ws.CloseAsync(CloseStatusCode.Normal, $"关闭连接{why}");
  144. }
  145. else {
  146. // 因为旧用户名密码没有成功连接过,说明旧用户名密码不正确,而现在用户名密码变更了,有可能变更正确了所以尝试连接一次。
  147. ConnectAsync(_ws);
  148. }
  149. }
  150. else if (_ws.ReadyState != WebSocketState.Open) {
  151. ConnectAsync(_ws);
  152. }
  153. }
  154. catch (Exception e) {
  155. Logger.ErrorDebugLine(e);
  156. }
  157. }
  158. #endregion
  159. #region GetWsDaemonState
  160. public WsClientState GetState() {
  161. var ws = _ws;
  162. string description = $"{_closeCode} {_closeReason}";
  163. WsClientStatus status = WsClientStatus.Closed;
  164. if (ws != null) {
  165. status = ws.ReadyState.ToWsClientStatus();
  166. if (status == WsClientStatus.Open) {
  167. description = status.GetDescription();
  168. }
  169. }
  170. var state = new WsClientState {
  171. Status = status,
  172. Description = description,
  173. NextTrySecondsDelay = NextTrySecondsDelay,
  174. LastTryOn = LastTryOn
  175. };
  176. return state;
  177. }
  178. #endregion
  179. #region 私有方法
  180. #region NewWebSocket
  181. /// <summary>
  182. /// 这是一次彻底的重连,重新获取服务器地址的重连,以下情况下才会调用该方法:
  183. /// 1,进程启动后第一次连接时;
  184. /// 2,连不上服务器时;
  185. /// 3,收到服务器的WsMessage.ReGetServerAddress类型的消息时;
  186. /// </summary>
  187. /// <returns></returns>
  188. private void NewWebSocket(Action<WebSocket> callback) {
  189. RpcRoot.OfficialServer.WsServerNodeService.GetNodeAddressAsync(NTMinerRegistry.GetClientId(_appType), _outerUserId, (response, ex) => {
  190. LastTryOn = DateTime.Now;
  191. if (!response.IsSuccess()) {
  192. IncreaseFailCount();
  193. UpdateNextTrySecondsDelay();
  194. string description;
  195. if (response == null || response.ReasonPhrase == null) {
  196. description = "网络错误";
  197. }
  198. else {
  199. description = response.ReadMessage(ex);
  200. }
  201. UpdateWsStateAsync(description, toOut: false);
  202. callback?.Invoke(null);
  203. // 退出
  204. return;
  205. }
  206. string server = response.Data;
  207. if (string.IsNullOrEmpty(server)) {
  208. IncreaseFailCount();
  209. UpdateNextTrySecondsDelay();
  210. UpdateWsStateAsync("服务器不在线", toOut: false);
  211. callback?.Invoke(null);
  212. // 退出
  213. return;
  214. }
  215. var ws = new WebSocket($"ws://{server}/{_appType.GetName()}");
  216. ws.OnOpen += (sender, e) => {
  217. ResetFailCount();
  218. UpdateWsStateAsync("连接服务器成功", toOut: false);
  219. };
  220. ws.OnMessage += (sender, e) => {
  221. if (_ws != ws) {
  222. return;
  223. }
  224. #region
  225. if (e.IsPing) {
  226. return;
  227. }
  228. WsMessage message = null;
  229. if (e.IsBinary) {
  230. message = VirtualRoot.BinarySerializer.Deserialize<WsMessage>(e.RawData);
  231. }
  232. else {// 此时一定IsText,因为取值只有IsBinary、IsPing、IsText这三种
  233. if (string.IsNullOrEmpty(e.Data) || e.Data[0] != '{' || e.Data[e.Data.Length - 1] != '}') {
  234. return;
  235. }
  236. message = VirtualRoot.JsonSerializer.Deserialize<WsMessage>(e.Data);
  237. }
  238. if (message == null) {
  239. return;
  240. }
  241. switch (_appType) {
  242. case NTMinerAppType.MinerClient:
  243. if (message.Type == WsMessage.UpdateAESPassword) {
  244. if (message.TryGetData(out AESPassword aesPassword)) {
  245. aesPassword.Password = Cryptography.RSAUtil.DecryptString(aesPassword.Password, aesPassword.PublicKey);
  246. _aesPassword = aesPassword;
  247. }
  248. return;
  249. }
  250. if (_aesPassword == null) {
  251. return;
  252. }
  253. if (message.Sign != message.CalcSign(_aesPassword.Password)) {
  254. UpdateWsStateAsync(description: "来自群控的消息签名错误", toOut: true);
  255. return;
  256. }
  257. break;
  258. case NTMinerAppType.MinerStudio:
  259. if (message.Type == WsMessage.ReLogin) {
  260. UpdateWsStateAsync(description: "用户密码已变更,请重新登录", toOut: true);
  261. return;
  262. }
  263. if (message.Sign != message.CalcSign(RpcRoot.RpcUser.Password)) {
  264. UpdateWsStateAsync(description: "来自群控的消息签名错误", toOut: true);
  265. return;
  266. }
  267. break;
  268. default:
  269. break;
  270. }
  271. if (message.Type == WsMessage.ReGetServerAddress) {
  272. ws.CloseAsync(CloseStatusCode.Normal, WsMessage.ReGetServerAddress);
  273. return;
  274. }
  275. if (TryGetHandler(message.Type, out Action<Action<WsMessage>, WsMessage> handler)) {
  276. handler.Invoke(SendAsync, message);
  277. }
  278. else {
  279. Write.DevWarn(() => $"OnMessage Received InvalidType {e.Data}");
  280. }
  281. #endregion
  282. };
  283. ws.OnError += (sender, e) => {
  284. Write.DevError(e.Message);
  285. };
  286. ws.OnClose += (sender, e) => {
  287. if (_ws != ws) {
  288. return;
  289. }
  290. #region
  291. try {
  292. LastTryOn = DateTime.Now;
  293. _closeCode = e.Code.ToString();
  294. CloseStatusCode closeStatus = (CloseStatusCode)e.Code;
  295. _closeCode = closeStatus.GetName();
  296. if (closeStatus == CloseStatusCode.ProtocolError) {
  297. IncreaseFailCount();
  298. // WebSocket协议并无定义状态码用于表达握手阶段身份验证失败的情况,阅读WebSocketSharp的源码发现验证不通过包含于ProtocolError中,
  299. // 姑且将ProtocolError视为用户名密码验证不通过,因为ProtocolError包含的其它失败情况在编程正确下不会发送。
  300. _closeReason = "登录失败";
  301. }
  302. else if (closeStatus == CloseStatusCode.Away) { // 服务器ping不通时和服务器关闭进程时都是Away
  303. IncreaseFailCount();
  304. _closeReason = "失去连接,请稍后重试";
  305. // 可能是因为服务器节点不存在导致的失败,所以下一次进行重新获取服务器地址的全新连接
  306. // 2,连不上服务器时
  307. _ws = null;
  308. }
  309. else if (closeStatus == CloseStatusCode.Abnormal) { // 服务器或本机网络不可用时尝试连接时的类型是Abnormal
  310. IncreaseFailCount();
  311. _closeReason = "网络错误";
  312. // 可能是因为服务器节点不存在导致的失败,所以下一次进行重新获取服务器地址的全新连接
  313. // 2,连不上服务器时
  314. _ws = null;
  315. }
  316. else if (closeStatus == CloseStatusCode.Normal) {
  317. _closeReason = e.Reason;
  318. if (e.Reason == WsMessage.ReGetServerAddress) {
  319. _closeReason = "服务器通知客户端重连";
  320. // 放在这里重连以防止在上一个连接关闭之前重连成功从而在界面上留下错误顺序的消息
  321. // 3,收到服务器的WsMessage.ReGetServerAddress类型的消息时
  322. NewWebSocket(webSocket => _ws = webSocket);
  323. }
  324. else {
  325. IncreaseFailCount();
  326. }
  327. }
  328. }
  329. catch {
  330. }
  331. UpdateNextTrySecondsDelay();
  332. UpdateWsStateAsync($"{_closeCode} {_closeReason}", toOut: false);
  333. #endregion
  334. };
  335. ConnectAsync(ws);
  336. callback?.Invoke(ws);
  337. });
  338. }
  339. #endregion
  340. #region ConnectAsync
  341. private readonly FieldInfo _retryCountForConnectFieldInfo = typeof(WebSocket).GetField("_retryCountForConnect", BindingFlags.Instance | BindingFlags.NonPublic);
  342. private void ConnectAsync(WebSocket ws) {
  343. if (ws == null) {
  344. return;
  345. }
  346. if (ws.ReadyState == WebSocketState.Open) {
  347. return;
  348. }
  349. // WebSocketSharp内部限定了连接重试次数,这不符合我们的业务逻辑,这里通过反射赋值使WebSocketSharp的重试次数限制失效。
  350. _retryCountForConnectFieldInfo.SetValue(ws, 1);
  351. WsUserName userName = new WsUserName {
  352. ClientType = _appType,
  353. ClientVersion = EntryAssemblyInfo.CurrentVersionStr,
  354. ClientId = NTMinerRegistry.GetClientId(_appType),
  355. UserId = _outerUserId,
  356. IsBinarySupported = true
  357. };
  358. string userNameJson = VirtualRoot.JsonSerializer.Serialize(userName);
  359. string password = string.Empty;
  360. if (_appType == NTMinerAppType.MinerStudio) {
  361. password = RpcRoot.RpcUser.Password;
  362. }
  363. string base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(userNameJson));
  364. password = HashUtil.Sha1(base64String + password);
  365. // SetCredentials要求username不能带:号,所以必须编码
  366. ws.SetCredentials(base64String, password, preAuth: true);
  367. LastTryOn = DateTime.Now;
  368. ws.ConnectAsync();
  369. }
  370. #endregion
  371. private void ResetFailCount() {
  372. _failConnCount = 0;
  373. _continueCount = 0;
  374. NextTrySecondsDelay = -1;
  375. }
  376. private void IncreaseFailCount() {
  377. _failConnCount++;
  378. }
  379. private void UpdateNextTrySecondsDelay() {
  380. NextTrySecondsDelay = (_failConnCount - _continueCount) * 10;
  381. if (NextTrySecondsDelay < -1) {
  382. NextTrySecondsDelay = -1;
  383. }
  384. }
  385. #endregion
  386. }
  387. }