Connector.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Net.Sockets;
  5. public enum enNetResult
  6. {
  7. Success = 0,
  8. Error,
  9. ConnectFailed,
  10. NetworkException,
  11. Timeout,
  12. InvalidArgument,
  13. LengthError,
  14. Unknown,
  15. Empty,
  16. }
  17. public class Connector : ISocketHandler
  18. {
  19. public const int RECV_BUFF_SIZE = 1024 * 1024;
  20. private readonly int BODY_MAX_LENGTH = 128 * 1024;
  21. private SocketConn mSocketConn = null;
  22. public Action ConnectEvent = null;
  23. public Action ReconnectEvent = null;
  24. public Action DisconnectEvent = null;
  25. public Action ErrorEvent = null;
  26. public Action ConnectFailedEvent = null;
  27. public Action TimeoutEvent = null;
  28. private string ip; //IP地址
  29. private int port; //端口
  30. private float m_fConnectTimeout = 5;
  31. private StateObject mStateObject = null;
  32. private byte[] mRecvBuffer = new byte[RECV_BUFF_SIZE];
  33. private byte[] mHeadBytes = new byte[NetPkgHead.HeadLength];
  34. private NetPkgHead mHead = null;
  35. public bool Connected { get; private set; }
  36. public Connector(string ip, int port)
  37. {
  38. this.ip = ip;
  39. this.port = port;
  40. Connected = false;
  41. mSocketConn = new SocketConn("tcp");
  42. mSocketConn.RegHandler(this);
  43. }
  44. public void CustomUpdate()
  45. {
  46. if (mSocketConn != null)
  47. mSocketConn.CustomUpdate();
  48. }
  49. public void Resume()
  50. {
  51. if (mSocketConn != null)
  52. mSocketConn.Resume();
  53. }
  54. public bool WriteData(byte[] data, int len)
  55. {
  56. try
  57. {
  58. if (data == null) return false;
  59. if (mSocketConn == null || mSocketConn.Sock == null || mSocketConn.State != enSocketState.Connected)
  60. return false;
  61. try
  62. {
  63. if (!mSocketConn.Sock.Poll(1, SelectMode.SelectWrite)) return false;
  64. mSocketConn.Sock.Send(data, 0, len, SocketFlags.None);
  65. return true;
  66. }
  67. catch (SocketException se)
  68. {
  69. Debug.LogError("Socket Send Exception: " + se.Message);
  70. OnError();
  71. }
  72. }
  73. catch (System.Exception ex)
  74. {
  75. Debug.LogError("Tcp Write Data Error: " + ex.Message);
  76. }
  77. return false;
  78. }
  79. public bool WriteData(byte[] data)
  80. {
  81. return WriteData(data, data.Length);
  82. }
  83. public bool ReadData(ref List<NetPkg> pkgList)
  84. {
  85. try
  86. {
  87. if (mSocketConn == null ||
  88. mSocketConn.Sock == null ||
  89. mSocketConn.State != enSocketState.Connected)
  90. {
  91. return false;
  92. }
  93. int recvSize = 0;
  94. try
  95. {
  96. if (!mSocketConn.Sock.Poll(1, SelectMode.SelectRead)) return false;
  97. recvSize = mSocketConn.Sock.Receive(mRecvBuffer, 0, RECV_BUFF_SIZE, SocketFlags.None);
  98. }
  99. catch (SocketException ex)
  100. {
  101. Debug.LogError(ex.Message);
  102. OnError();
  103. return false;
  104. }
  105. if (recvSize <= 0)
  106. {
  107. return false;
  108. }
  109. //收到的字节长度以及数据处理
  110. int ret = received(mRecvBuffer, recvSize, ref pkgList);
  111. if (ret == 0)
  112. {
  113. return true;
  114. }
  115. }
  116. catch (Exception e)
  117. {
  118. Debug.LogError(e.Message);
  119. }
  120. return false;
  121. }
  122. private int received(byte[] buffer, int bytesRead, ref List<NetPkg> pkgList)
  123. {
  124. mStateObject.Write(buffer, bytesRead);
  125. while (true)
  126. {
  127. int len = (int)mStateObject.stream.Length;
  128. if (len == 0)
  129. {
  130. break;
  131. }
  132. if ((mStateObject.ReceiveBody &&
  133. len < (mStateObject.BuffLength)) ||
  134. (!mStateObject.ReceiveBody && len < NetPkgHead.HeadLength))
  135. {
  136. DebugHelper.LogWarning(string.Format("[ GeminiRPC.dataReceived ]parsed all data.cmdid:{2} remain length:{0}, BuffLength:{1}", len, mStateObject.BuffLength, mStateObject.CmdId));
  137. return 1;
  138. }
  139. if ((!mStateObject.ReceiveBody) && (len >= NetPkgHead.HeadLength))
  140. {
  141. long origPos = mStateObject.stream.Position;
  142. mStateObject.stream.Position = 0;
  143. ResetBytes();
  144. mStateObject.stream.Read(mHeadBytes, 0, (int)NetPkgHead.HeadLength);
  145. mStateObject.stream.Position = origPos;
  146. if (mHead == null)
  147. mHead = new NetPkgHead();
  148. int temp = 0;
  149. CommError.Type ret = mHead.unpack(ref mHeadBytes, (int)NetPkgHead.HeadLength, ref temp);
  150. if (ret == CommError.Type.COMM_NO_ERROR)
  151. {
  152. mStateObject.BodyLength = mHead.PkgLen;
  153. mStateObject.BuffLength = (uint)mHead.PkgLen + NetPkgHead.HeadLength;
  154. mStateObject.CmdId = mHead.CmdId;
  155. }
  156. else
  157. {
  158. DebugHelper.LogError(string.Format("[ GeminiRPC.dataReceived ]unpack pkg head failed:{0},{1}", ret, temp));
  159. }
  160. mStateObject.ReceiveBody = true;
  161. if (mStateObject.BodyLength >= BODY_MAX_LENGTH)
  162. {
  163. DebugHelper.LogError(string.Format("[ GeminiRPC.receivedHeader ]huge message, body length:{0}.", mStateObject.BodyLength));
  164. return -1;
  165. }
  166. }
  167. if ((mStateObject.ReceiveBody) && (len >= mStateObject.BuffLength))
  168. {
  169. if (mStateObject.buffer.Length < mStateObject.BuffLength)
  170. {
  171. mStateObject.buffer = new byte[mStateObject.BuffLength + 1024 - mStateObject.BuffLength % 1024];
  172. }
  173. byte[] data_bytes = mStateObject.buffer;
  174. mStateObject.stream.Position = 0;
  175. mStateObject.stream.Read(data_bytes, 0, (int)mStateObject.BuffLength);
  176. int buffLen = (int)mStateObject.BuffLength;
  177. int parseSize = 0;
  178. NetPkg msg = NetPkg.CreateNetRevPkg();
  179. CommError.Type ret = msg.unpack(ref data_bytes, buffLen, ref parseSize);
  180. if (ret == CommError.Type.COMM_NO_ERROR)
  181. {
  182. pkgList.Add(msg);
  183. }
  184. else
  185. {
  186. DebugHelper.LogError(string.Format("unpack socket buffer error,ret:{0}", (int)ret));
  187. DebugHelper.LogError(string.Format("unpack socket buffer error,CmdId:{0} totoal len={1}", mStateObject.CmdId, buffLen));
  188. }
  189. mStateObject.Reset();
  190. }
  191. }
  192. return 0;
  193. }
  194. private void ResetBytes()
  195. {
  196. for (int idx = 0; idx < mHeadBytes.Length; idx++)
  197. mHeadBytes[idx] = 0;
  198. }
  199. public bool Connect()
  200. {
  201. if (mSocketConn == null) return false;
  202. if (mStateObject != null)
  203. {
  204. mStateObject.Dispose();
  205. mStateObject = null;
  206. }
  207. mStateObject = new StateObject();
  208. mHead = new NetPkgHead();
  209. return mSocketConn.Connect(this.ip, this.port, m_fConnectTimeout);
  210. }
  211. public bool Connect(float timeout)
  212. {
  213. m_fConnectTimeout = timeout;
  214. return Connect();
  215. }
  216. public bool Reconnect()
  217. {
  218. if (mSocketConn == null) return false;
  219. return mSocketConn.Reconnect();
  220. }
  221. public enNetResult Reconnect(float timeout)
  222. {
  223. return enNetResult.Empty;
  224. }
  225. public void Disconnect()
  226. {
  227. if (mSocketConn != null)
  228. {
  229. mSocketConn.Disconnect();
  230. }
  231. }
  232. public void OnConnect()
  233. {
  234. Connected = true;
  235. if (ConnectEvent != null)
  236. ConnectEvent();
  237. }
  238. public void OnReconnect()
  239. {
  240. Connected = true;
  241. if (ReconnectEvent != null)
  242. ReconnectEvent();
  243. }
  244. public void OnDisconnect()
  245. {
  246. Connected = false;
  247. if (DisconnectEvent != null)
  248. DisconnectEvent();
  249. }
  250. public void OnTimeout()
  251. {
  252. Debug.Log("Connect Timeout");
  253. if (TimeoutEvent != null)
  254. TimeoutEvent();
  255. }
  256. public void OnError()
  257. {
  258. Connected = false;
  259. Debug.LogError("Connect Error");
  260. if (ErrorEvent != null)
  261. ErrorEvent();
  262. }
  263. public void OnConnectFailed()
  264. {
  265. Connected = false;
  266. if (ConnectFailedEvent != null)
  267. ConnectFailedEvent();
  268. }
  269. public void OnException(System.Net.Sockets.SocketException se)
  270. {
  271. Debug.LogError(se.Message);
  272. mSocketConn.Disconnect();
  273. }
  274. }