TcpSocketServer.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using Aitex.Core.RT.Log;
  7. using MECF.Framework.Common.Communications.Tcp.Socket.Server.APM.EventArgs;
  8. namespace MECF.Framework.Common.Communications.Tcp.Socket.Server.APM
  9. {
  10. public class TcpSocketServer
  11. {
  12. #region Fields
  13. //private static readonly ILogger _log = LoggerManager.GetLogger(Assembly.GetExecutingAssembly(), "Tcp");//. .Get<TcpSocketClient>();
  14. private TcpListener _listener;
  15. private readonly ConcurrentDictionary<string, TcpSocketSession> _sessions = new ConcurrentDictionary<string, TcpSocketSession>();
  16. private readonly TcpSocketServerConfiguration _configuration;
  17. private readonly object _opsLock = new object();
  18. private bool _isListening = false;
  19. #endregion
  20. #region Constructors
  21. public TcpSocketServer(int listenedPort, TcpSocketServerConfiguration configuration = null)
  22. : this(IPAddress.Any, listenedPort, configuration)
  23. {
  24. }
  25. public TcpSocketServer(IPAddress listenedAddress, int listenedPort, TcpSocketServerConfiguration configuration = null)
  26. : this(new IPEndPoint(listenedAddress, listenedPort), configuration)
  27. {
  28. }
  29. public TcpSocketServer(IPEndPoint listenedEndPoint, TcpSocketServerConfiguration configuration = null)
  30. {
  31. if (listenedEndPoint == null)
  32. throw new ArgumentNullException("listenedEndPoint");
  33. this.ListenedEndPoint = listenedEndPoint;
  34. _configuration = configuration ?? new TcpSocketServerConfiguration();
  35. if (_configuration.BufferManager == null)
  36. throw new InvalidProgramException("The buffer manager in configuration cannot be null.");
  37. if (_configuration.FrameBuilder == null)
  38. throw new InvalidProgramException("The frame handler in configuration cannot be null.");
  39. }
  40. #endregion
  41. #region Properties
  42. public IPEndPoint ListenedEndPoint { get; set; }
  43. public bool IsListening { get { return _isListening; } }
  44. public int SessionCount { get { return _sessions.Count; } }
  45. #endregion
  46. #region Server
  47. public void Listen()
  48. {
  49. lock (_opsLock)
  50. {
  51. if (_isListening)
  52. return;
  53. _listener = new TcpListener(this.ListenedEndPoint);
  54. //SetSocketOptions();
  55. _isListening = true;
  56. _listener.Start(_configuration.PendingConnectionBacklog);
  57. ContinueAcceptSession(_listener);
  58. }
  59. }
  60. public void Shutdown()
  61. {
  62. lock (_opsLock)
  63. {
  64. if (!_isListening)
  65. return;
  66. try
  67. {
  68. _isListening = false;
  69. _listener.Stop();
  70. foreach (var session in _sessions.Values)
  71. {
  72. CloseSession(session);
  73. }
  74. _sessions.Clear();
  75. _listener = null;
  76. }
  77. catch (Exception ex)
  78. {
  79. if (!ShouldThrow(ex))
  80. {
  81. LOG.Error(ex.Message, ex);
  82. }
  83. else throw;
  84. }
  85. }
  86. }
  87. public bool Pending()
  88. {
  89. lock (_opsLock)
  90. {
  91. if (!_isListening)
  92. throw new InvalidOperationException("The server is not listening.");
  93. // determine if there are pending connection requests.
  94. return _listener.Pending();
  95. }
  96. }
  97. private void SetSocketOptions()
  98. {
  99. _listener.AllowNatTraversal(_configuration.AllowNatTraversal);
  100. _listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, _configuration.ReuseAddress);
  101. }
  102. private void ContinueAcceptSession(TcpListener listener)
  103. {
  104. try
  105. {
  106. listener.BeginAcceptTcpClient(new AsyncCallback(HandleTcpClientAccepted), listener);
  107. }
  108. catch (Exception ex)
  109. {
  110. if (!ShouldThrow(ex))
  111. {
  112. LOG.Error(ex.Message, ex);
  113. }
  114. else throw;
  115. }
  116. }
  117. private void HandleTcpClientAccepted(IAsyncResult ar)
  118. {
  119. if (!_isListening)
  120. return;
  121. try
  122. {
  123. TcpListener listener = (TcpListener)ar.AsyncState;
  124. TcpClient tcpClient = listener.EndAcceptTcpClient(ar);
  125. if (!tcpClient.Connected)
  126. return;
  127. var session = new TcpSocketSession(tcpClient, _configuration, _configuration.BufferManager, this);
  128. bool isSessionStarted = false;
  129. try
  130. {
  131. _sessions.AddOrUpdate(session.SessionKey, session, (n, o) => { return o; });
  132. session.Start();
  133. isSessionStarted = true;
  134. }
  135. catch (Exception ex)
  136. {
  137. LOG.Error(ex.Message, ex);
  138. }
  139. if (isSessionStarted)
  140. {
  141. ContinueAcceptSession(listener);
  142. }
  143. else
  144. {
  145. CloseSession(session);
  146. }
  147. }
  148. catch (Exception ex)
  149. {
  150. if (!ShouldThrow(ex))
  151. {
  152. LOG.Error(ex.Message, ex);
  153. }
  154. else throw;
  155. }
  156. }
  157. private void CloseSession(TcpSocketSession session)
  158. {
  159. TcpSocketSession sessionToBeThrowAway;
  160. _sessions.TryRemove(session.SessionKey, out sessionToBeThrowAway);
  161. if (session != null)
  162. {
  163. session.Close();
  164. }
  165. }
  166. private bool ShouldThrow(Exception ex)
  167. {
  168. if (ex is ObjectDisposedException
  169. || ex is InvalidOperationException
  170. || ex is SocketException
  171. || ex is IOException)
  172. {
  173. return false;
  174. }
  175. return false;
  176. }
  177. #endregion
  178. #region Send
  179. private void GuardRunning()
  180. {
  181. if (!_isListening)
  182. throw new InvalidProgramException("This tcp server has not been started yet.");
  183. }
  184. public void SendTo(string sessionKey, byte[] data)
  185. {
  186. GuardRunning();
  187. if (string.IsNullOrEmpty(sessionKey))
  188. throw new ArgumentNullException("sessionKey");
  189. if (data == null)
  190. throw new ArgumentNullException("data");
  191. SendTo(sessionKey, data, 0, data.Length);
  192. }
  193. public void SendTo(string sessionKey, byte[] data, int offset, int count)
  194. {
  195. GuardRunning();
  196. if (string.IsNullOrEmpty(sessionKey))
  197. throw new ArgumentNullException("sessionKey");
  198. if (data == null)
  199. throw new ArgumentNullException("data");
  200. TcpSocketSession session = null;
  201. if (_sessions.TryGetValue(sessionKey, out session))
  202. {
  203. session.Send(data, offset, count);
  204. }
  205. else
  206. {
  207. LOG.Warning(string.Format("Cannot find session [{0}].", sessionKey));
  208. }
  209. }
  210. public void SendTo(TcpSocketSession session, byte[] data)
  211. {
  212. GuardRunning();
  213. if (session == null)
  214. throw new ArgumentNullException("session");
  215. if (data == null)
  216. throw new ArgumentNullException("data");
  217. SendTo(session, data, 0, data.Length);
  218. }
  219. public void SendTo(TcpSocketSession session, byte[] data, int offset, int count)
  220. {
  221. GuardRunning();
  222. if (session == null)
  223. throw new ArgumentNullException("session");
  224. if (data == null)
  225. throw new ArgumentNullException("data");
  226. TcpSocketSession writeSession = null;
  227. if (_sessions.TryGetValue(session.SessionKey, out writeSession))
  228. {
  229. session.Send(data, offset, count);
  230. }
  231. else
  232. {
  233. LOG.Warning(string.Format("Cannot find session [{0}].", session));
  234. }
  235. }
  236. public void BeginSendTo(string sessionKey, byte[] data)
  237. {
  238. GuardRunning();
  239. if (string.IsNullOrEmpty(sessionKey))
  240. throw new ArgumentNullException("sessionKey");
  241. if (data == null)
  242. throw new ArgumentNullException("data");
  243. BeginSendTo(sessionKey, data, 0, data.Length);
  244. }
  245. public void BeginSendTo(string sessionKey, byte[] data, int offset, int count)
  246. {
  247. GuardRunning();
  248. if (string.IsNullOrEmpty(sessionKey))
  249. throw new ArgumentNullException("sessionKey");
  250. if (data == null)
  251. throw new ArgumentNullException("data");
  252. TcpSocketSession session = null;
  253. if (_sessions.TryGetValue(sessionKey, out session))
  254. {
  255. session.BeginSend(data, offset, count);
  256. }
  257. else
  258. {
  259. LOG.Warning(string.Format("Cannot find session [{0}].", sessionKey));
  260. }
  261. }
  262. public void BeginSendTo(TcpSocketSession session, byte[] data)
  263. {
  264. GuardRunning();
  265. if (session == null)
  266. throw new ArgumentNullException("session");
  267. if (data == null)
  268. throw new ArgumentNullException("data");
  269. BeginSendTo(session, data, 0, data.Length);
  270. }
  271. public void BeginSendTo(TcpSocketSession session, byte[] data, int offset, int count)
  272. {
  273. GuardRunning();
  274. if (session == null)
  275. throw new ArgumentNullException("session");
  276. if (data == null)
  277. throw new ArgumentNullException("data");
  278. TcpSocketSession writeSession = null;
  279. if (_sessions.TryGetValue(session.SessionKey, out writeSession))
  280. {
  281. session.BeginSend(data, offset, count);
  282. }
  283. else
  284. {
  285. LOG.Warning(string.Format("Cannot find session [{0}].", session));
  286. }
  287. }
  288. public IAsyncResult BeginSendTo(string sessionKey, byte[] data, AsyncCallback callback, object state)
  289. {
  290. if (data == null)
  291. throw new ArgumentNullException("data");
  292. return BeginSendTo(sessionKey, data, 0, data.Length, callback, state);
  293. }
  294. public IAsyncResult BeginSendTo(string sessionKey, byte[] data, int offset, int count, AsyncCallback callback, object state)
  295. {
  296. GuardRunning();
  297. if (string.IsNullOrEmpty(sessionKey))
  298. throw new ArgumentNullException("sessionKey");
  299. if (data == null)
  300. throw new ArgumentNullException("data");
  301. TcpSocketSession session = null;
  302. if (_sessions.TryGetValue(sessionKey, out session))
  303. {
  304. return session.BeginSend(data, offset, count, callback, state);
  305. }
  306. else
  307. {
  308. LOG.Warning(string.Format("Cannot find session [{0}].", sessionKey));
  309. }
  310. return null;
  311. }
  312. public IAsyncResult BeginSendTo(TcpSocketSession session, byte[] data, AsyncCallback callback, object state)
  313. {
  314. GuardRunning();
  315. if (session == null)
  316. throw new ArgumentNullException("session");
  317. if (data == null)
  318. throw new ArgumentNullException("data");
  319. return BeginSendTo(session, data, 0, data.Length, callback, state);
  320. }
  321. public IAsyncResult BeginSendTo(TcpSocketSession session, byte[] data, int offset, int count, AsyncCallback callback, object state)
  322. {
  323. GuardRunning();
  324. if (session == null)
  325. throw new ArgumentNullException("session");
  326. if (data == null)
  327. throw new ArgumentNullException("data");
  328. TcpSocketSession writeSession = null;
  329. if (_sessions.TryGetValue(session.SessionKey, out writeSession))
  330. {
  331. return session.BeginSend(data, offset, count, callback, state);
  332. }
  333. else
  334. {
  335. LOG.Warning(string.Format("Cannot find session [{0}].", session));
  336. }
  337. return null;
  338. }
  339. public void EndSendTo(string sessionKey, IAsyncResult asyncResult)
  340. {
  341. GuardRunning();
  342. if (string.IsNullOrEmpty(sessionKey))
  343. throw new ArgumentNullException("sessionKey");
  344. TcpSocketSession session = null;
  345. if (_sessions.TryGetValue(sessionKey, out session))
  346. {
  347. session.EndSend(asyncResult);
  348. }
  349. }
  350. public void EndSendTo(TcpSocketSession session, IAsyncResult asyncResult)
  351. {
  352. GuardRunning();
  353. if (session == null)
  354. throw new ArgumentNullException("session");
  355. TcpSocketSession writeSession = null;
  356. if (_sessions.TryGetValue(session.SessionKey, out writeSession))
  357. {
  358. session.EndSend(asyncResult);
  359. }
  360. }
  361. public void Broadcast(byte[] data)
  362. {
  363. GuardRunning();
  364. if (data == null)
  365. throw new ArgumentNullException("data");
  366. Broadcast(data, 0, data.Length);
  367. }
  368. public void Broadcast(byte[] data, int offset, int count)
  369. {
  370. GuardRunning();
  371. if (data == null)
  372. throw new ArgumentNullException("data");
  373. foreach (var session in _sessions.Values)
  374. {
  375. session.Send(data, offset, count);
  376. }
  377. }
  378. public void BeginBroadcast(byte[] data)
  379. {
  380. GuardRunning();
  381. if (data == null)
  382. throw new ArgumentNullException("data");
  383. BeginBroadcast(data, 0, data.Length);
  384. }
  385. public void BeginBroadcast(byte[] data, int offset, int count)
  386. {
  387. GuardRunning();
  388. if (data == null)
  389. throw new ArgumentNullException("data");
  390. foreach (var session in _sessions.Values)
  391. {
  392. session.BeginSend(data, offset, count);
  393. }
  394. }
  395. #endregion
  396. #region Session
  397. public bool HasSession(string sessionKey)
  398. {
  399. return _sessions.ContainsKey(sessionKey);
  400. }
  401. public TcpSocketSession GetSession(string sessionKey)
  402. {
  403. TcpSocketSession session = null;
  404. _sessions.TryGetValue(sessionKey, out session);
  405. return session;
  406. }
  407. public void CloseSession(string sessionKey)
  408. {
  409. TcpSocketSession session = null;
  410. if (_sessions.TryGetValue(sessionKey, out session))
  411. {
  412. session.Close();
  413. }
  414. }
  415. #endregion
  416. #region Events
  417. public event EventHandler<TcpClientConnectedEventArgs> ClientConnected;
  418. public event EventHandler<TcpClientDisconnectedEventArgs> ClientDisconnected;
  419. public event EventHandler<TcpClientDataReceivedEventArgs> ClientDataReceived;
  420. internal void RaiseClientConnected(TcpSocketSession session)
  421. {
  422. try
  423. {
  424. if (ClientConnected != null)
  425. {
  426. ClientConnected(this, new TcpClientConnectedEventArgs(session));
  427. }
  428. }
  429. catch (Exception ex)
  430. {
  431. HandleUserSideError(session, ex);
  432. }
  433. }
  434. internal void RaiseClientDisconnected(TcpSocketSession session)
  435. {
  436. try
  437. {
  438. if (ClientDisconnected != null)
  439. {
  440. ClientDisconnected(this, new TcpClientDisconnectedEventArgs(session));
  441. }
  442. }
  443. catch (Exception ex)
  444. {
  445. HandleUserSideError(session, ex);
  446. }
  447. finally
  448. {
  449. TcpSocketSession sessionToBeThrowAway;
  450. _sessions.TryRemove(session.SessionKey, out sessionToBeThrowAway);
  451. }
  452. }
  453. internal void RaiseClientDataReceived(TcpSocketSession session, byte[] data, int dataOffset, int dataLength)
  454. {
  455. try
  456. {
  457. if (ClientDataReceived != null)
  458. {
  459. ClientDataReceived(this, new TcpClientDataReceivedEventArgs(session, data, dataOffset, dataLength));
  460. }
  461. }
  462. catch (Exception ex)
  463. {
  464. HandleUserSideError(session, ex);
  465. }
  466. }
  467. private void HandleUserSideError(TcpSocketSession session, Exception ex)
  468. {
  469. LOG.Error(string.Format("Session [{0}] error occurred in user side [{1}].", session, ex.Message), ex);
  470. }
  471. #endregion
  472. }
  473. }