ConnectionClient.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. using Island.StandardLib.Exceptions;
  2. using Island.StandardLib.Storage;
  3. using System;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7. namespace Island.StandardLib
  8. {
  9. public abstract class ConnectionClient
  10. {
  11. public string ServerAddress { get; private set; }
  12. public int ServerPort { get; private set; }
  13. public int MaxBitSize { get; private set; }
  14. public bool DebugMode { get; set; }
  15. public uint ClientVersion { get; private set; }
  16. public ConnectionClient(string addr, int port, uint version = 1, bool debug = false, int maxbitsz = 524288)
  17. {
  18. ServerAddress = addr;
  19. ServerPort = port;
  20. ClientVersion = version;
  21. MaxBitSize = maxbitsz;
  22. DebugMode = debug;
  23. }
  24. public ConnectObjectFromClient CommandSendPool;
  25. public Socket ClientSocket;
  26. public bool IsConnected { get; private set; }
  27. Thread clientLoop;
  28. /// <summary>
  29. /// 自定义登录动作完成后调用此函数开启通信循环
  30. /// </summary>
  31. public void KeepConnect()
  32. {
  33. if (clientLoop != null) if (clientLoop.IsAlive)
  34. throw new PlayerSocketFatalException("client", PlayerSocketFatalExceptionType.InternalDuplicatePlayerThreadStart);
  35. clientLoop = new Thread(ClientLoop) { IsBackground = true };
  36. clientLoop.Start();
  37. //KeepConnect<int, object>()(default);
  38. }
  39. //public Func<TIn, TOut> KeepConnect<TIn, TOut>() where TIn : struct where TOut : class
  40. //{
  41. // return t =>
  42. // {
  43. // KeepConnect();
  44. // Func<TOut> func = () =>
  45. // {
  46. // return default(TOut);
  47. // };
  48. // };
  49. //}
  50. public LoginResult ConnectAsLogin<RequestType>(RequestType request)
  51. where RequestType : ILoginOrRegisterRequest, IStorable, new()
  52. {
  53. try
  54. {
  55. request.ClientVersion = ClientVersion;
  56. request.IsLogin = true;
  57. IPAddress[] addr = Dns.GetHostAddresses(ServerAddress);
  58. ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  59. ClientSocket.Connect(addr, ServerPort);
  60. ClientSocket.SendOnce(request);
  61. LoginCallback lcb = ClientSocket.ReceiveOnce<LoginCallback>(512);
  62. if (lcb.Success)
  63. {
  64. KeepConnect();
  65. }
  66. else
  67. {
  68. try
  69. {
  70. ClientSocket.Close();
  71. ClientSocket.Dispose();
  72. }
  73. catch { }
  74. }
  75. return lcb.Code;
  76. }
  77. catch (Exception)
  78. {
  79. try
  80. {
  81. ClientSocket?.Close();
  82. ClientSocket?.Dispose();
  83. }
  84. catch { }
  85. return LoginResult.ConnectionError;
  86. }
  87. }
  88. public RegisterData ConnectAsRegister<RequestType>(RequestType request)
  89. where RequestType : ILoginOrRegisterRequest, IStorable, new()
  90. {
  91. try
  92. {
  93. request.IsLogin = false;
  94. IPAddress[] addr = Dns.GetHostAddresses(ServerAddress);
  95. Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  96. sock.Connect(addr, ServerPort);
  97. sock.SendOnce(request);
  98. RegisterCallback rcb = sock.ReceiveOnce<RegisterCallback>(512);
  99. try
  100. {
  101. sock.Close();
  102. sock.Dispose();
  103. }
  104. catch { }
  105. if (rcb.Success) return new RegisterData(RegisterResult.Success, rcb.Username);
  106. else return new RegisterData((RegisterResult)rcb.Username, -1);
  107. }
  108. catch
  109. {
  110. return new RegisterData(RegisterResult.ConnectionError, -1);
  111. }
  112. }
  113. public void ConnectAsRegister<RequestType>(RequestType request, out RegisterCallback rcb)
  114. where RequestType : ILoginOrRegisterRequest, IStorable, new()
  115. {
  116. try
  117. {
  118. request.IsLogin = false;
  119. IPAddress[] addr = Dns.GetHostAddresses(ServerAddress);
  120. Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  121. sock.Connect(addr, ServerPort);
  122. sock.SendOnce(request);
  123. rcb = sock.ReceiveOnce<RegisterCallback>(512);
  124. try
  125. {
  126. sock.Close();
  127. sock.Dispose();
  128. }
  129. catch { }
  130. }
  131. catch
  132. {
  133. rcb = null;
  134. }
  135. }
  136. public T ConnectManual<T>(byte[] bSend) where T : IStorable, new()
  137. {
  138. try
  139. {
  140. IPAddress[] addr = Dns.GetHostAddresses(ServerAddress);
  141. Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  142. sock.Connect(addr, ServerPort);
  143. sock.SendOnce(bSend);
  144. T ret = sock.ReceiveOnce<T>(2048);
  145. try
  146. {
  147. sock.Close();
  148. sock.Dispose();
  149. }
  150. catch { }
  151. return ret;
  152. }
  153. catch
  154. {
  155. return default;
  156. }
  157. }
  158. //public LoginResult ConnectAsLogin(int userName, string password)
  159. //{
  160. // try
  161. // {
  162. // LoginOrRegisterRequest request = new LoginOrRegisterRequest(userName, password, ClientVersion);
  163. // request.IsLogin = true;
  164. // IPAddress[] addr = Dns.GetHostAddresses(ServerAddress);
  165. // ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  166. // ClientSocket.Connect(addr, ServerPort);
  167. // ClientSocket.SendOnce(request);
  168. // LoginCallback lcb = ClientSocket.ReceiveOnce<LoginCallback>(512);
  169. // if (lcb.Success)
  170. // {
  171. // Thread clientLoop = new Thread(ClientLoop);
  172. // clientLoop.IsBackground = true;
  173. // clientLoop.Start();
  174. // //Thread watchLoop = new Thread(WatcherLoop);
  175. // //watchLoop.IsBackground = true;
  176. // //watchLoop.Start();
  177. // }
  178. // else
  179. // {
  180. // try
  181. // {
  182. // ClientSocket.Close();
  183. // ClientSocket.Dispose();
  184. // }
  185. // catch { }
  186. // }
  187. // return lcb.Code;
  188. // }
  189. // catch (Exception e)
  190. // {
  191. // try
  192. // {
  193. // ClientSocket?.Close();
  194. // ClientSocket?.Dispose();
  195. // }
  196. // catch { }
  197. // return LoginResult.ConnectionError;
  198. // }
  199. //}
  200. //public RegisterData ConnectAsRegister(string nickname, string password)
  201. //{
  202. // try
  203. // {
  204. // LoginOrRegisterRequest request = new LoginOrRegisterRequest(0, password, ClientVersion);
  205. // request.IsRegister = true;
  206. // request.Nickname = nickname;
  207. // IPAddress[] addr = Dns.GetHostAddresses(ServerAddress);
  208. // Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  209. // sock.Connect(addr, ServerPort);
  210. // sock.SendOnce(request);
  211. // RegisterCallback rcb = sock.ReceiveOnce<RegisterCallback>(512);
  212. // try
  213. // {
  214. // sock.Close();
  215. // sock.Dispose();
  216. // }
  217. // catch { }
  218. // if (rcb.Success) return new RegisterData(RegisterResult.Success, rcb.Username);
  219. // else return new RegisterData((RegisterResult)rcb.Username, -1);
  220. // }
  221. // catch
  222. // {
  223. // return new RegisterData(RegisterResult.ConnectionError, -1);
  224. // }
  225. //}
  226. //void WatcherLoop()
  227. //{
  228. // while (true)
  229. // {
  230. // contFlag = false;
  231. // Thread.Sleep(5000);
  232. // if (!contFlag)
  233. // {
  234. // IsConnected = false;
  235. // OnConnectionBreaked(new Exception("Wait too long"));
  236. // }
  237. // }
  238. //}
  239. bool contFlag = true;
  240. public void Shutdown() => contFlag = false;
  241. public virtual void OnClientWillSendDataToServer(ConnectObjectFromServer serverData) { }
  242. void ClientLoop()
  243. {
  244. Exception endWith;
  245. CommandSendPool = new ConnectObjectFromClient();
  246. IsConnected = true;
  247. OnConnectionBegin();
  248. ClientSocket.SendTimeout = 5000;
  249. ClientSocket.ReceiveTimeout = 5000;
  250. while (true)
  251. {
  252. try
  253. {
  254. ConnectObjectFromServer serverData = ClientSocket.ReceiveOnce<ConnectObjectFromServer>(MaxBitSize);
  255. if (!contFlag) throw new Exception("Shutdown flag enabled.");
  256. bool recvCmds, sendCmds;
  257. lock (CommandSendPool)
  258. {
  259. InnerCommandPass(serverData);
  260. OnClientWillSendDataToServer(serverData);
  261. ClientSocket.SendOnce(CommandSendPool);
  262. recvCmds = serverData.Commands.Count != 0;
  263. sendCmds = CommandSendPool.Commands.Count != 0;
  264. CommandSendPool.ClearCommands();
  265. }
  266. if (DebugMode)
  267. {
  268. if (recvCmds && sendCmds)
  269. {
  270. Console.BackgroundColor = ConsoleColor.Red;
  271. Console.Write("x");
  272. }
  273. else if (recvCmds)
  274. {
  275. Console.BackgroundColor = ConsoleColor.DarkBlue;
  276. Console.Write("-");
  277. }
  278. else if (sendCmds)
  279. {
  280. Console.BackgroundColor = ConsoleColor.DarkGreen;
  281. Console.Write("+");
  282. }
  283. else
  284. {
  285. Console.BackgroundColor = ConsoleColor.Black;
  286. Console.Write("=");
  287. }
  288. }
  289. }
  290. catch (Exception e)
  291. {
  292. endWith = e;
  293. break;
  294. }
  295. }
  296. try
  297. {
  298. ClientSocket.Close();
  299. ClientSocket.Dispose();
  300. }
  301. catch { }
  302. IsConnected = false;
  303. BreakedException = endWith;
  304. OnConnectionBreaked(endWith);
  305. }
  306. public Exception BreakedException;
  307. void InnerCommandPass(ConnectObjectFromServer serverData)
  308. {
  309. for (int i = 0; i < serverData.Commands.Length; i++)
  310. {
  311. ConnectCommand command = serverData.Commands[i];
  312. PassCommand(command);
  313. }
  314. }
  315. protected abstract void PassCommand(ConnectCommand command);
  316. protected virtual void OnConnectionBegin() { }
  317. protected virtual void OnConnectionBreaked(Exception reason) { }
  318. }
  319. public struct RegisterData
  320. {
  321. public RegisterData(RegisterResult r, int u)
  322. {
  323. result = r;
  324. uid = u;
  325. }
  326. public RegisterResult result;
  327. public int uid;
  328. }
  329. }