Network.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using System.Collections.Concurrent;
  2. using System.Net.Sockets;
  3. using Client.MirControls;
  4. using C = ClientPackets;
  5. namespace Client.MirNetwork
  6. {
  7. static class Network
  8. {
  9. private static TcpClient _client;
  10. public static int ConnectAttempt = 0;
  11. public static int MaxAttempts = 20;
  12. public static bool ErrorShown;
  13. public static bool Connected;
  14. public static long TimeOutTime, TimeConnected, RetryTime = CMain.Time + 5000;
  15. private static ConcurrentQueue<Packet> _receiveList;
  16. private static ConcurrentQueue<Packet> _sendList;
  17. static byte[] _rawData = new byte[0];
  18. static readonly byte[] _rawBytes = new byte[8 * 1024];
  19. public static void Connect()
  20. {
  21. if (_client != null)
  22. Disconnect();
  23. if (ConnectAttempt >= MaxAttempts)
  24. {
  25. if (ErrorShown)
  26. {
  27. return;
  28. }
  29. ErrorShown = true;
  30. MirMessageBox errorBox = new(GameLanguage.ClientTextMap.GetLocalization(ClientTextKeys.ErrorConnectingToServer), MirMessageBoxButtons.Cancel);
  31. errorBox.CancelButton.Click += (o, e) => Program.Form.Close();
  32. errorBox.Label.Text = GameLanguage.ClientTextMap.GetLocalization((ClientTextKeys.MaximumConnectionAttemptsReached), MaxAttempts);
  33. errorBox.Show();
  34. return;
  35. }
  36. ConnectAttempt++;
  37. try
  38. {
  39. _client = new TcpClient { NoDelay = true };
  40. _client?.BeginConnect(Settings.IPAddress, Settings.Port, Connection, null);
  41. }
  42. catch (ObjectDisposedException ex)
  43. {
  44. if (Settings.LogErrors) CMain.SaveError(ex.ToString());
  45. Disconnect();
  46. }
  47. }
  48. private static void Connection(IAsyncResult result)
  49. {
  50. try
  51. {
  52. _client?.EndConnect(result);
  53. if ((_client != null &&
  54. !_client.Connected) ||
  55. _client == null)
  56. {
  57. Connect();
  58. return;
  59. }
  60. _receiveList = new ConcurrentQueue<Packet>();
  61. _sendList = new ConcurrentQueue<Packet>();
  62. _rawData = new byte[0];
  63. TimeOutTime = CMain.Time + Settings.TimeOut;
  64. TimeConnected = CMain.Time;
  65. BeginReceive();
  66. }
  67. catch (SocketException)
  68. {
  69. Thread.Sleep(100);
  70. Connect();
  71. }
  72. catch (Exception ex)
  73. {
  74. if (Settings.LogErrors) CMain.SaveError(ex.ToString());
  75. Disconnect();
  76. }
  77. }
  78. private static void BeginReceive()
  79. {
  80. if (_client == null || !_client.Connected) return;
  81. try
  82. {
  83. _client.Client.BeginReceive(_rawBytes, 0, _rawBytes.Length, SocketFlags.None, ReceiveData, _rawBytes);
  84. }
  85. catch
  86. {
  87. Disconnect();
  88. }
  89. }
  90. private static void ReceiveData(IAsyncResult result)
  91. {
  92. if (_client == null || !_client.Connected) return;
  93. int dataRead;
  94. try
  95. {
  96. dataRead = _client.Client.EndReceive(result);
  97. }
  98. catch
  99. {
  100. Disconnect();
  101. return;
  102. }
  103. if (dataRead == 0)
  104. {
  105. Disconnect();
  106. }
  107. byte[] rawBytes = result.AsyncState as byte[];
  108. byte[] temp = _rawData;
  109. _rawData = new byte[dataRead + temp.Length];
  110. Buffer.BlockCopy(temp, 0, _rawData, 0, temp.Length);
  111. Buffer.BlockCopy(rawBytes, 0, _rawData, temp.Length, dataRead);
  112. Packet p;
  113. List<byte> data = new List<byte>();
  114. while ((p = Packet.ReceivePacket(_rawData, out _rawData)) != null)
  115. {
  116. data.AddRange(p.GetPacketBytes());
  117. _receiveList.Enqueue(p);
  118. }
  119. CMain.BytesReceived += data.Count;
  120. BeginReceive();
  121. }
  122. private static void BeginSend(List<byte> data)
  123. {
  124. if (_client == null || !_client.Connected || data.Count == 0) return;
  125. try
  126. {
  127. _client.Client.BeginSend(data.ToArray(), 0, data.Count, SocketFlags.None, SendData, null);
  128. }
  129. catch
  130. {
  131. Disconnect();
  132. }
  133. }
  134. private static void SendData(IAsyncResult result)
  135. {
  136. try
  137. {
  138. _client.Client.EndSend(result);
  139. }
  140. catch
  141. { }
  142. }
  143. public static void Disconnect()
  144. {
  145. if (_client == null) return;
  146. _client?.Close();
  147. TimeConnected = 0;
  148. Connected = false;
  149. _sendList = null;
  150. _client = null;
  151. _receiveList = null;
  152. }
  153. public static void Process()
  154. {
  155. if (_client == null || !_client.Connected)
  156. {
  157. if (Connected)
  158. {
  159. while (_receiveList != null && !_receiveList.IsEmpty)
  160. {
  161. if (!_receiveList.TryDequeue(out Packet p) || p == null) continue;
  162. if (!(p is ServerPackets.Disconnect) && !(p is ServerPackets.ClientVersion)) continue;
  163. MirScene.ActiveScene.ProcessPacket(p);
  164. _receiveList = null;
  165. return;
  166. }
  167. MirMessageBox.Show(GameLanguage.ClientTextMap.GetLocalization(ClientTextKeys.LostConnectionWithServer), true);
  168. Disconnect();
  169. return;
  170. }
  171. else if (CMain.Time >= RetryTime)
  172. {
  173. RetryTime = CMain.Time + 5000;
  174. Connect();
  175. }
  176. return;
  177. }
  178. if (!Connected && TimeConnected > 0 && CMain.Time > TimeConnected + 5000)
  179. {
  180. Disconnect();
  181. Connect();
  182. return;
  183. }
  184. while (_receiveList != null && !_receiveList.IsEmpty)
  185. {
  186. if (!_receiveList.TryDequeue(out Packet p) || p == null) continue;
  187. MirScene.ActiveScene.ProcessPacket(p);
  188. }
  189. if (CMain.Time > TimeOutTime && _sendList != null && _sendList.IsEmpty)
  190. _sendList.Enqueue(new C.KeepAlive());
  191. if (_sendList == null || _sendList.IsEmpty) return;
  192. TimeOutTime = CMain.Time + Settings.TimeOut;
  193. List<byte> data = new List<byte>();
  194. while (!_sendList.IsEmpty)
  195. {
  196. if (!_sendList.TryDequeue(out Packet p)) continue;
  197. data.AddRange(p.GetPacketBytes());
  198. }
  199. CMain.BytesSent += data.Count;
  200. BeginSend(data);
  201. }
  202. public static void Enqueue(Packet p)
  203. {
  204. if (_sendList != null && p != null)
  205. _sendList.Enqueue(p);
  206. }
  207. }
  208. }