SNetSession.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. using CommonLang;
  2. using CommonLang.ByteOrder;
  3. using CommonLang.IO;
  4. using CommonLang.Net;
  5. using CommonLang.Protocol;
  6. using CommonNetwork.Net;
  7. using CommonNetwork.Utils;
  8. using SuperSocket.ClientEngine;
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Net.Sockets;
  16. using System.Text;
  17. using System.Threading;
  18. namespace CommonNetwork_SSocket.SuperSocket
  19. {
  20. public class SNetSession : INetSession
  21. {
  22. private string mURL;
  23. private IPEndPoint mRemoteAddress;
  24. private AsyncTcpSession mTCP = null;
  25. protected INetPackageCodec mCodec;
  26. private INetSessionListener mListener;
  27. private HashMap<string, object> mAttributes = new HashMap<string, object>();
  28. private long mSendBytes = 0;
  29. private long mRecvBytes = 0;
  30. private long mSendPacks = 0;
  31. private long mRecvPacks = 0;
  32. public SNetSession()
  33. {
  34. }
  35. public long TotalSentBytes { get { return mSendBytes; } }
  36. public long TotalRecvBytes { get { return mRecvBytes; } }
  37. public long TotalSentPackages { get { return mSendPacks; } }
  38. public long TotalRecvPackages { get { return mRecvPacks; } }
  39. public string URL { get { return mURL; } }
  40. public IPEndPoint RemoteAddress { get { return mRemoteAddress; } }
  41. /// <summary>
  42. /// 判断当前网络是否已经连接
  43. /// </summary>
  44. /// <returns></returns>
  45. public bool IsConnected
  46. {
  47. get
  48. {
  49. AsyncTcpSession tcp = mTCP;
  50. if (tcp != null)
  51. {
  52. return tcp.IsConnected;
  53. }
  54. return false;
  55. }
  56. }
  57. public bool Open(string url, INetPackageCodec codec, INetSessionListener listener)
  58. {
  59. bool ret = false;
  60. try
  61. {
  62. lock (this)
  63. {
  64. if (mTCP == null)
  65. {
  66. this.mCodec = codec;
  67. this.mListener = listener;
  68. this.mURL = url;
  69. string[] url_kv = url.Split(':');
  70. this.mRemoteAddress = IPUtil.ToEndPoint(url_kv[0], int.Parse(url_kv[1]));//new IPEndPoint(IPAddress.Parse(url_kv[0]), int.Parse(url_kv[1]));
  71. //this.mLocalAddress = IPUtil.CreateLocalConnectorEndPoint();//new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0);
  72. //this.mRecvQueue.Clear();
  73. // 建立SOCKET链接
  74. this.mTCP = new AsyncTcpSession(mRemoteAddress);
  75. this.mTCP.Closed += mTCP_Closed;
  76. this.mTCP.Connected += mTCP_Connected;
  77. this.mTCP.DataReceived += mTCP_DataReceived;
  78. this.mTCP.Error += mTCP_Error;
  79. this.mTCP.NoDeplay = true;
  80. this.mTCP.Connect();
  81. ret = true;
  82. return ret;
  83. }
  84. }
  85. }
  86. catch (Exception err)
  87. {
  88. onException(new NetException("/n[Open:]" + URL +
  89. "/n[InnerException:]" + err.InnerException +
  90. "/n[Exception:]" + err.Message +
  91. "/n[Source:]" + err.Source +
  92. "/n[StackTrace:]" + err.StackTrace));
  93. }
  94. return ret;
  95. }
  96. private void mTCP_Error(object sender, global::SuperSocket.ClientEngine.ErrorEventArgs e)
  97. {
  98. try
  99. {
  100. this.onException(e.Exception);
  101. }
  102. catch (Exception err) { }
  103. }
  104. private void mTCP_Connected(object sender, EventArgs e)
  105. {
  106. try
  107. {
  108. this.onOpen();
  109. }
  110. catch (Exception err) { }
  111. }
  112. private void mTCP_Closed(object sender, EventArgs e)
  113. {
  114. try
  115. {
  116. this.onClose();
  117. }
  118. catch (Exception err) { }
  119. }
  120. private void mTCP_DataReceived(object sender, DataEventArgs e)
  121. {
  122. try
  123. {
  124. doDecode(e);
  125. }
  126. catch (Exception err)
  127. {
  128. try
  129. {
  130. this.onException(err);
  131. }
  132. catch (Exception err2) { }
  133. }
  134. }
  135. public bool Close()
  136. {
  137. bool ret = false;
  138. lock (this)
  139. {
  140. if (mTCP != null)
  141. {
  142. try
  143. {
  144. this.mTCP.Close();
  145. }
  146. catch (Exception err)
  147. {
  148. }
  149. this.mTCP = null;
  150. ret = true;
  151. }
  152. }
  153. return ret;
  154. }
  155. public void Dispose()
  156. {
  157. Close();
  158. }
  159. //-------------------------------------------------------------------------------------
  160. /// <summary>
  161. /// 发送一个消息,该方法将立即返回。
  162. /// </summary>
  163. /// <param name="data"></param>
  164. public void Send(Object data)
  165. {
  166. if (mTCP != null)
  167. {
  168. ArraySegment<byte> send;
  169. if (doEncode(data, out send))
  170. {
  171. if (mTCP.TrySend(send))
  172. {
  173. onSent(data);
  174. }
  175. }
  176. }
  177. }
  178. public void SendResponse(IMessage rsponse, int requestMessageID)
  179. {
  180. rsponse.MessageID = requestMessageID;
  181. Send(rsponse);
  182. }
  183. //-------------------------------------------------------------------------------------
  184. public object GetAttribute(string key)
  185. {
  186. return mAttributes[key];
  187. }
  188. public void SetAttribute(string key, object value)
  189. {
  190. mAttributes[key] = value;
  191. }
  192. public void RemoveAttribute(string key)
  193. {
  194. mAttributes.Remove(key);
  195. }
  196. public bool ContainsAttribute(string key)
  197. {
  198. return mAttributes.ContainsKey(key);
  199. }
  200. public ICollection<string> GetAttributeKeys()
  201. {
  202. return mAttributes.Keys;
  203. }
  204. override public string ToString()
  205. {
  206. return "Session[" + URL + "](" + GetHashCode() + ")";
  207. }
  208. //-------------------------------------------------------------------------------------
  209. private void onClose()
  210. {
  211. mListener.sessionClosed(this);
  212. if (mOnSessionClosed != null)
  213. {
  214. mOnSessionClosed.Invoke(this);
  215. }
  216. }
  217. private void onOpen()
  218. {
  219. mListener.sessionOpened(this);
  220. if (mOnSessionOpened != null)
  221. {
  222. mOnSessionOpened.Invoke(this);
  223. }
  224. }
  225. private void onReceive(Object message)
  226. {
  227. try
  228. {
  229. mListener.messageReceived(this, message);
  230. if (mOnMessageReceived != null)
  231. {
  232. mOnMessageReceived.Invoke(this, message);
  233. }
  234. }
  235. catch (Exception err)
  236. {
  237. onException(err);
  238. }
  239. }
  240. private void onSent(Object message)
  241. {
  242. mListener.messageSent(this, message);
  243. if (mOnMessageSent != null)
  244. {
  245. mOnMessageSent.Invoke(this, message);
  246. }
  247. }
  248. private void onException(Exception err)
  249. {
  250. mListener.onError(this, err);
  251. if (mOnError != null)
  252. {
  253. mOnError.Invoke(this, err);
  254. }
  255. }
  256. //-------------------------------------------------------------------------------------
  257. private OnSessionOpenedHandler mOnSessionOpened;
  258. private OnSessionClosedHandler mOnSessionClosed;
  259. private OnMessageReceivedHandler mOnMessageReceived;
  260. private OnMessageSentHandler mOnMessageSent;
  261. private OnErrorHandler mOnError;
  262. public event OnSessionOpenedHandler OnSessionOpened { add { mOnSessionOpened += value; } remove { mOnSessionOpened -= value; } }
  263. public event OnSessionClosedHandler OnSessionClosed { add { mOnSessionClosed += value; } remove { mOnSessionClosed -= value; } }
  264. public event OnMessageReceivedHandler OnMessageReceived { add { mOnMessageReceived += value; } remove { mOnMessageReceived -= value; } }
  265. public event OnMessageSentHandler OnMessageSent { add { mOnMessageSent += value; } remove { mOnMessageSent -= value; } }
  266. public event OnErrorHandler OnError { add { mOnError += value; } remove { mOnError -= value; } }
  267. //-------------------------------------------------------------------------------------
  268. private MemoryStream send_buff = new MemoryStream(8192);
  269. private ReceiveBuffer recv_buff = new ReceiveBuffer(8192);
  270. private Queue<object> decoding_queue = new Queue<object>();
  271. protected virtual bool doEncode(object send_msg, out ArraySegment<byte> send)
  272. {
  273. lock (send_buff)
  274. {
  275. send_buff.Position = 0;
  276. LittleEdian.PutS32(send_buff, 0);
  277. if (mCodec.doEncode(send_buff, send_msg))
  278. {
  279. send = new ArraySegment<byte>(send_buff.GetBuffer(), 0, (int)send_buff.Position);
  280. send_buff.Position = 0;
  281. LittleEdian.PutS32(send_buff, send.Count - 4);
  282. return true;
  283. }
  284. }
  285. throw new Exception("Can not encode message : " + send_msg);
  286. }
  287. private void doDecode(DataEventArgs input)
  288. {
  289. lock (recv_buff)
  290. {
  291. recv_buff.Put(input.Data, input.Offset, input.Length);
  292. recv_buff.Begin();
  293. object message;
  294. while (doDecodeOnce(recv_buff, out message))
  295. {
  296. recv_buff.Over();
  297. if (message != null)
  298. {
  299. lock (decoding_queue)
  300. {
  301. decoding_queue.Enqueue(message);
  302. }
  303. }
  304. }
  305. }
  306. lock (decoding_queue)
  307. {
  308. while (decoding_queue.Count > 0)
  309. {
  310. onReceive(decoding_queue.Dequeue());
  311. }
  312. }
  313. }
  314. protected virtual bool doDecodeOnce(ReceiveBuffer buff, out object message)
  315. {
  316. if (buff.Remaining >= 4)
  317. {
  318. int length = LittleEdian.GetS32(recv_buff.Stream);
  319. if (buff.Remaining >= length)
  320. {
  321. mCodec.doDecode(buff.Stream, out message);
  322. return true;
  323. }
  324. }
  325. message = null;
  326. return false;
  327. }
  328. }
  329. }