SocketServer.cs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. 
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Windows.Forms;
  10. using Curtain.Net.Sockets.PLC.Model;
  11. namespace Curtain.Net.Sockets.PLC
  12. {
  13. /// <summary>
  14. /// Socket 服务端
  15. /// </summary>
  16. public class SocketServer : PLCSocket
  17. {
  18. /// <summary>
  19. /// 在线客户端
  20. /// </summary>
  21. //private Dictionary<ClientSession, IServerModel> _factory = new Dictionary<Type, IServerModel>();
  22. protected Dictionary<string, ClientSession> clients = new Dictionary<string, ClientSession>();
  23. #region 属性
  24. /// <summary>
  25. /// 服务所在winform窗体(异步事件响应用)
  26. /// </summary>
  27. public Control OwnerForm
  28. {
  29. get;
  30. set;
  31. }
  32. /// <summary>
  33. /// 服务状态
  34. /// </summary>
  35. public bool Started
  36. {
  37. get;
  38. protected set;
  39. }
  40. /// <summary>
  41. /// 服务端模型
  42. /// </summary>
  43. public virtual IServerModel Model
  44. {
  45. get
  46. {
  47. return null;
  48. }
  49. }
  50. /// <summary>
  51. /// 通信超时(毫秒)
  52. /// </summary>
  53. public int ReceiveTimeout
  54. {
  55. get; set;
  56. }
  57. /// <summary>
  58. /// 通信超时(毫秒)
  59. /// </summary>
  60. public int SendTimeout
  61. {
  62. get; set;
  63. }
  64. /// <summary>
  65. /// 服务端Session
  66. /// </summary>
  67. public ServerSession ServerSession
  68. {
  69. get;
  70. protected set;
  71. }
  72. /// <summary>
  73. /// 接收服务启动异常后自动重试次数
  74. /// </summary>
  75. private int _repeated = 3;
  76. /// <summary>
  77. /// 接收服务启动异常后自动重试次数(默认3次,最大20次)
  78. /// </summary>
  79. public int Repeated
  80. {
  81. get
  82. {
  83. return _repeated;
  84. }
  85. set
  86. {
  87. if (value < 0)
  88. {
  89. _repeated = 0;
  90. }
  91. else if (value > 20)
  92. {
  93. _repeated = 20;
  94. }
  95. else
  96. {
  97. _repeated = value;
  98. }
  99. }
  100. }
  101. #endregion
  102. #region 构造
  103. /// <summary>
  104. /// Socket 服务端
  105. /// </summary>
  106. public SocketServer()
  107. {
  108. }
  109. #endregion
  110. #region 事件
  111. /// <summary>
  112. /// 服务启动前
  113. /// </summary>
  114. public event CancelEventHandler ServerStarting;
  115. /// <summary>
  116. /// 服务启动后
  117. /// </summary>
  118. public event CancelEventHandler ServerStoping;
  119. /// <summary>
  120. /// 服务停止前
  121. /// </summary>
  122. public event EventHandler ServerStarted;
  123. /// <summary>
  124. /// 服务停止后
  125. /// </summary>
  126. public event EventHandler ServerStoped;
  127. /// <summary>
  128. /// 服务端事件发生
  129. /// </summary>
  130. public event ServerMessageEventHandler ServerMessage;
  131. /// <summary>
  132. /// 服务启动前
  133. /// </summary>
  134. protected virtual void OnServerStarting(CancelEventArgs e)
  135. {
  136. ServerStarting?.Invoke(this, e);
  137. }
  138. /// <summary>
  139. /// 服务启动后
  140. /// </summary>
  141. protected virtual void OnServerStoping(CancelEventArgs e)
  142. {
  143. ServerStoping?.Invoke(this, e);
  144. }
  145. /// <summary>
  146. /// 服务停止前
  147. /// </summary>
  148. protected virtual void OnServerStarted(EventArgs e)
  149. {
  150. ServerStarted?.Invoke(this, e);
  151. }
  152. /// <summary>
  153. /// 服务停止后
  154. /// </summary>
  155. protected virtual void OnServerStoped(EventArgs e)
  156. {
  157. ServerStoped?.Invoke(this, e);
  158. }
  159. /// <summary>
  160. /// 服务端事件发生
  161. /// </summary>
  162. protected virtual void OnServerMessage(ServerMessageEventArgs e)
  163. {
  164. if (OwnerForm?.InvokeRequired ?? false)
  165. {
  166. OwnerForm.BeginInvoke(new Action<ServerMessageEventArgs>(OnServerMessage), e);
  167. return;
  168. }
  169. ServerMessage?.Invoke(this, e);
  170. }
  171. /// <summary>
  172. /// 完成数据接收
  173. /// </summary>
  174. /// <param name="sender"></param>
  175. /// <param name="e"></param>
  176. public delegate void ReceivedEventHandler(object sender, ReceiveSession e);
  177. /// <summary>
  178. /// 完成数据接收
  179. /// </summary>
  180. public event ReceivedEventHandler Received;
  181. /// <summary>
  182. /// 完成数据接收
  183. /// </summary>
  184. /// <param name="rs"></param>
  185. protected virtual void OnReceived(ReceiveSession rs)
  186. {
  187. //Framework.Log.Logger.Debug("OnReceived", "timeout");
  188. if (OwnerForm?.InvokeRequired ?? false)
  189. {
  190. OwnerForm.BeginInvoke(new Action<ReceiveSession>(OnReceived), rs);
  191. return;
  192. }
  193. Received?.Invoke(this, rs);
  194. }
  195. #endregion
  196. #region Accept
  197. /// <summary>
  198. /// 开始接收客户端消息
  199. /// </summary>
  200. /// <param name="iar"></param>
  201. protected void AcceptCallback(IAsyncResult iar)
  202. {
  203. if (!this.Started || this.Socket == null)
  204. {
  205. // 服务器已停止
  206. return;
  207. }
  208. if (iar.AsyncState is ServerSession ss)
  209. {
  210. if (ss == null || ss.Socket == null)
  211. {
  212. // 服务已停止
  213. return;
  214. }
  215. Socket clientSocket = null;
  216. ClientSession cs = new ClientSession();
  217. clients.Add(cs.ID, cs);
  218. try
  219. {
  220. clientSocket = ss.Socket.EndAccept(iar);
  221. cs.Server = ss;
  222. cs.Socket = clientSocket;
  223. try
  224. {
  225. cs.IPEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
  226. }
  227. catch (Exception ex)
  228. {
  229. ServerMessageEventArgs e1 = new ServerMessageEventArgs
  230. {
  231. Type = ServerMessageType.Debug,
  232. Code = "CNS-D-001",
  233. Message = "客户端IP异常",
  234. Exception = ex,
  235. Client = cs,
  236. Server = ss
  237. };
  238. this.OnServerMessage(e1);
  239. }
  240. ServerMessageEventArgs e = new ServerMessageEventArgs
  241. {
  242. Type = ServerMessageType.Trace,
  243. Code = "CNS-T-000",
  244. Message = $"客户端 {cs} 已连接",
  245. Client = cs,
  246. Server = ss
  247. };
  248. this.OnServerMessage(e);
  249. ThreadPool.QueueUserWorkItem(new WaitCallback(OnClientConnected), cs);
  250. }
  251. catch (ObjectDisposedException ex)
  252. {
  253. // 服务已停止
  254. OnServerDownError(ss, ex);
  255. return;
  256. }
  257. catch (Exception ex)
  258. {
  259. ServerMessageEventArgs e = new ServerMessageEventArgs
  260. {
  261. Type = ServerMessageType.Error,
  262. Code = "CNS-E-000",
  263. Message = "客户端已关闭",
  264. Exception = ex,
  265. Client = cs,
  266. Server = ss
  267. };
  268. this.OnServerMessage(e);
  269. //clientSocket?.Close();
  270. CloseClientSocket(cs);
  271. }
  272. //如果失败,尝试重新启动
  273. int i = 0;
  274. while (i < _repeated)
  275. {
  276. try
  277. {
  278. ss.Socket.BeginAccept(new AsyncCallback(AcceptCallback), ss);
  279. break;
  280. }
  281. catch (Exception ex)
  282. {
  283. i++;
  284. ServerMessageEventArgs e = new ServerMessageEventArgs
  285. {
  286. Type = ServerMessageType.Error,
  287. Code = "CNS-E-001",
  288. Message = "服务启动失败,尝试重启( " + i + " / " + _repeated + " )",
  289. Exception = ex,
  290. Server = ss
  291. };
  292. this.OnServerMessage(e);
  293. Thread.Sleep(1000);
  294. }
  295. }
  296. if (i >= _repeated)
  297. {
  298. ServerMessageEventArgs e = new ServerMessageEventArgs
  299. {
  300. Type = ServerMessageType.Error,
  301. Code = "CNS-E-002",
  302. Message = "服务尝试重启失败",
  303. //e.Exception = ex;
  304. Server = ss
  305. };
  306. this.OnServerMessage(e);
  307. this.StopCore();
  308. }
  309. }
  310. }
  311. /// <summary>
  312. /// 开始接收
  313. /// </summary>
  314. /// <param name="cs"></param>
  315. protected virtual void StartReceive(ClientSession cs)
  316. {
  317. if (!(cs.Socket.Connected))
  318. {
  319. ServerMessageEventArgs e = new ServerMessageEventArgs
  320. {
  321. Type = ServerMessageType.Trace,
  322. Code = "CNS-T-002",
  323. Message = $"客户端 {cs} 已关闭",
  324. Client = cs,
  325. Server = cs.Server
  326. };
  327. this.OnServerMessage(e);
  328. return;
  329. }
  330. int length = Model.HeadLength;
  331. if (length < 1)
  332. {
  333. ServerMessageEventArgs e = new ServerMessageEventArgs
  334. {
  335. Type = ServerMessageType.Error,
  336. Code = "CNS-E-003",
  337. Message = Model.GetType().ToString() + ".HeadLength<1",
  338. Client = cs,
  339. Server = cs.Server
  340. };
  341. this.OnServerMessage(e);
  342. return;
  343. }
  344. ReceiveSession rs = new ReceiveSession
  345. {
  346. ServerSocket = this,
  347. Client = cs,
  348. Offset = 0,
  349. Size = length
  350. };
  351. try
  352. {
  353. rs.HeadBytes = new byte[length];
  354. //cs.Socket.ReceiveTimeout = 0;//this.ReceiveTimeout;
  355. //Framework.Log.Logger.Debug("StartReceive", "timeout");
  356. cs.Socket.BeginReceive(rs.HeadBytes, rs.Offset, rs.Size, SocketFlags.None,
  357. HeadReceiveCallback, rs);
  358. }
  359. catch (Exception ex)
  360. {
  361. //OnReceiveException(rs, ex);
  362. OnClientDown(rs, ex);
  363. }
  364. }
  365. /// <summary>
  366. /// 指令头接收方法
  367. /// </summary>
  368. /// <param name="ar">异步状态信息</param>
  369. protected virtual void HeadReceiveCallback(IAsyncResult ar)
  370. {
  371. if (!this.Started || this.Socket == null)
  372. {
  373. // 服务器已停止
  374. return;
  375. }
  376. //Framework.Log.Logger.Debug("HeadReceiveCallback=0", "timeout");
  377. if (ar.AsyncState is ReceiveSession rs)
  378. {
  379. if (rs.Client == null || rs.Client.Socket == null)
  380. {
  381. // 服务器已停止
  382. return;
  383. }
  384. try
  385. {
  386. int receiveCount = rs.Client.Socket.EndReceive(ar);
  387. //Framework.Log.Logger.Debug("HeadReceiveCallback-1:receiveCount="+ receiveCount, "timeout");
  388. if (receiveCount == 0)
  389. {
  390. if (rs.Offset > 0)
  391. {
  392. OnClientTimeout(rs);
  393. }
  394. else
  395. {
  396. OnClientDown(rs);
  397. }
  398. return;
  399. }
  400. else
  401. {
  402. rs.Offset += receiveCount;
  403. }
  404. }
  405. catch (ObjectDisposedException)
  406. {
  407. // 客户端Socket已关闭(接收超时)
  408. //OnReceiveTimeout(rs);
  409. // 服务已停止
  410. //OnServerDownError(rs.Client.Server, ex);
  411. return;
  412. }
  413. catch (SocketException ex)
  414. {
  415. // 已经断开连接了
  416. //OnReceiveException(rs, ex);
  417. OnClientDown(rs, ex);
  418. return;
  419. }
  420. catch (Exception ex)
  421. {
  422. OnReceiveException(rs, ex, true);
  423. return;
  424. }
  425. if (rs.Offset < rs.Size)
  426. {
  427. try
  428. {
  429. // 继续接收,超时重启
  430. //Framework.Log.Logger.Debug("HeadReceiveCallback-2:继续接收,超时重启", "timeout");
  431. //rs.Client.Socket.ReceiveTimeout = this.ReceiveTimeout;
  432. //rs.Client.Socket.BeginReceive(rs.HeadBytes, rs.Offset, rs.Size - rs.Offset,
  433. // SocketFlags.None, HeadReceiveCallback, rs);
  434. rs.Client.Socket.BeginReceiveByTimeout(rs.HeadBytes, rs.Offset, rs.Size - rs.Offset, SocketFlags.None,
  435. HeadReceiveCallback, HeadReceiveCallbackTimeout, this.ReceiveTimeout, rs);
  436. }
  437. catch (Exception ex)
  438. {
  439. //OnReceiveException(rs, ex);
  440. OnClientDown(rs, ex);
  441. }
  442. return;
  443. }
  444. try
  445. {
  446. //rs.Head = ServerModel.ToCommandFromReceive(rs.HeadBytes);
  447. // 验证数据头
  448. if (!Model.CheckHead(rs))
  449. {
  450. ServerMessageEventArgs e = new ServerMessageEventArgs
  451. {
  452. Type = ServerMessageType.Warning,
  453. Code = "CNS-W-000",
  454. Message = "接收的数据头格式不正确",
  455. Client = rs.Client,
  456. Server = rs.Client.Server
  457. };
  458. CloseClientSocket(rs);
  459. this.OnServerMessage(e);
  460. return;
  461. }
  462. if (Model.FormatType == CommandFormatType.StartStopChar)
  463. {
  464. StringBuilder sbContent = new StringBuilder();
  465. bool isEscapeChar = false;
  466. List<byte> listByte = new List<byte>();
  467. try
  468. {
  469. while (true)
  470. {
  471. byte[] bytes = new byte[1];
  472. rs.Client.Socket.ReceiveTimeout = this.ReceiveTimeout;
  473. int receiveCount = rs.Client.Socket.Receive(bytes, 0, 1, SocketFlags.None);
  474. if (receiveCount == 0)
  475. {
  476. OnClientDown(rs);
  477. return;
  478. }
  479. char[] chars = Encoding.ASCII.GetChars(bytes);
  480. if (!isEscapeChar)
  481. {
  482. if (chars[0] == this.Model.EscapeChar)
  483. {
  484. isEscapeChar = true;
  485. continue;
  486. }
  487. if (chars[0] == this.Model.StopChar)
  488. {
  489. break;
  490. }
  491. }
  492. isEscapeChar = false;
  493. listByte.AddRange(bytes);
  494. sbContent.Append(chars[0]);
  495. }
  496. rs.ContentBytes = listByte.ToArray();
  497. rs.Content = sbContent.ToString();
  498. StartReceive(rs.Client);
  499. OnReceived(rs);
  500. }
  501. catch (Exception ex)
  502. {
  503. OnClientDown(rs, ex);
  504. }
  505. return;
  506. }
  507. int length = Model.GetContentLength(rs);
  508. if (length > 0)
  509. {
  510. rs.Offset = 0;
  511. rs.Size = length;
  512. try
  513. {
  514. rs.ContentBytes = new byte[length];
  515. // 正文接收,超时重启
  516. //Framework.Log.Logger.Debug("HeadReceiveCallback-3:Content="+ length, "timeout");
  517. //rs.Client.Socket.ReceiveTimeout = this.ReceiveTimeout;
  518. //rs.Client.Socket.BeginReceive(rs.ContentBytes, rs.Offset, rs.Size,
  519. // SocketFlags.None, ContentReceiveCallback, rs);
  520. rs.Client.Socket.BeginReceiveByTimeout(rs.ContentBytes, rs.Offset, rs.Size, SocketFlags.None,
  521. ContentReceiveCallback, ContentReceiveCallbackTimeout, this.ReceiveTimeout, rs);
  522. }
  523. catch (Exception ex)
  524. {
  525. //OnReceiveException(rs, ex);
  526. OnClientDown(rs, ex);
  527. }
  528. }
  529. else if (length < 0)
  530. {
  531. ServerMessageEventArgs e = new ServerMessageEventArgs
  532. {
  533. Type = ServerMessageType.Warning,
  534. Code = "CNS-W-001",
  535. Message = "接收的数据头格式不正确(文本长度)",
  536. Client = rs.Client,
  537. Server = rs.Client.Server
  538. };
  539. CloseClientSocket(rs);
  540. this.OnServerMessage(e);
  541. }
  542. else
  543. {
  544. StartReceive(rs.Client);
  545. OnReceived(rs);
  546. }
  547. }
  548. catch (Exception ex)
  549. {
  550. OnReceiveException(rs, ex);
  551. }
  552. }
  553. }
  554. /// <summary>
  555. /// 消息头接收超时
  556. /// </summary>
  557. /// <param name="ar"></param>
  558. protected virtual void HeadReceiveCallbackTimeout(IAsyncResult ar)
  559. {
  560. if (!this.Started || this.Socket == null)
  561. {
  562. // 服务器已停止
  563. return;
  564. }
  565. //Framework.Log.Logger.Debug("HeadReceiveCallbackTimeout:头接收超时", "timeout");
  566. if (ar.AsyncState is ReceiveSession rs)
  567. {
  568. if (rs.Client == null || rs.Client.Socket == null)
  569. {
  570. // 服务器已停止
  571. return;
  572. }
  573. OnReceiveTimeout(rs, true);
  574. }
  575. }
  576. /// <summary>
  577. /// 数据内容接收方法
  578. /// </summary>
  579. /// <param name="ar"></param>
  580. protected virtual void ContentReceiveCallback(IAsyncResult ar)
  581. {
  582. if (!this.Started || this.Socket == null)
  583. {
  584. // 服务器已停止
  585. return;
  586. }
  587. //Framework.Log.Logger.Debug("ContentReceiveCallback=0", "timeout");
  588. if (ar.AsyncState is ReceiveSession rs)
  589. {
  590. if (rs.Client == null || rs.Client.Socket == null)
  591. {
  592. // 服务器已停止
  593. return;
  594. }
  595. try
  596. {
  597. int receiveCount = rs.Client.Socket.EndReceive(ar);
  598. //Framework.Log.Logger.Debug("ContentReceiveCallback-1:receiveCount=" + receiveCount, "timeout");
  599. if (receiveCount == 0)
  600. {
  601. if (rs.Offset > 0)
  602. {
  603. OnClientTimeout(rs);
  604. }
  605. else
  606. {
  607. OnClientDown(rs);
  608. }
  609. return;
  610. }
  611. else
  612. {
  613. rs.Offset += receiveCount;
  614. }
  615. }
  616. catch (ObjectDisposedException)
  617. {
  618. // 客户端Socket已关闭(接收超时)
  619. //OnReceiveTimeout(rs);
  620. // 服务已停止
  621. //OnServerDownError(rs.Client.Server, ex);
  622. return;
  623. }
  624. catch (SocketException ex)
  625. {
  626. // 已经断开连接了
  627. //OnReceiveException(rs, ex);
  628. OnClientDown(rs, ex);
  629. return;
  630. }
  631. catch (Exception ex)
  632. {
  633. OnReceiveException(rs, ex, true);
  634. return;
  635. }
  636. if (rs.Offset < rs.Size)
  637. {
  638. try
  639. {
  640. // 继续接收,超时重启
  641. //Framework.Log.Logger.Debug("ContentReceiveCallback-2:继续接收,超时重启", "timeout");
  642. //rs.Client.Socket.ReceiveTimeout = this.ReceiveTimeout;
  643. //rs.Client.Socket.BeginReceive(rs.ContentBytes, rs.Offset, rs.Size - rs.Offset,
  644. // SocketFlags.None, ContentReceiveCallback, rs);
  645. rs.Client.Socket.BeginReceiveByTimeout(rs.ContentBytes, rs.Offset, rs.Size - rs.Offset, SocketFlags.None,
  646. ContentReceiveCallback, ContentReceiveCallbackTimeout, this.ReceiveTimeout, rs);
  647. }
  648. catch (Exception ex)
  649. {
  650. //OnReceiveException(rs, ex);
  651. OnClientDown(rs, ex);
  652. }
  653. return;
  654. }
  655. rs.Content = Model.ToContentFromReceive(rs.ContentBytes);
  656. StartReceive(rs.Client);
  657. OnReceived(rs);
  658. }
  659. }
  660. /// <summary>
  661. /// 数据内容接收超时
  662. /// </summary>
  663. /// <param name="ar"></param>
  664. protected virtual void ContentReceiveCallbackTimeout(IAsyncResult ar)
  665. {
  666. if (!this.Started || this.Socket == null)
  667. {
  668. // 服务器已停止
  669. return;
  670. }
  671. //Framework.Log.Logger.Debug("ContentReceiveCallbackTimeout:正文接收超时", "timeout");
  672. if (ar.AsyncState is ReceiveSession rs)
  673. {
  674. if (rs.Client == null || rs.Client.Socket == null)
  675. {
  676. // 服务器已停止
  677. return;
  678. }
  679. OnReceiveTimeout(rs, false);
  680. }
  681. }
  682. #endregion
  683. #region 事件处理
  684. /// <summary>
  685. /// 客户端上线
  686. /// </summary>
  687. /// <param name="state">session</param>
  688. protected virtual void OnClientConnected(object state)
  689. {
  690. if (state is ClientSession cs)
  691. {
  692. ServerMessageEventArgs e = new ServerMessageEventArgs
  693. {
  694. Type = ServerMessageType.Trace,
  695. Code = "CNS-T-001",
  696. Message = $"客户端 {cs} 已准备",
  697. Client = cs,
  698. Server = cs.Server
  699. };
  700. this.OnServerMessage(e);
  701. this.StartReceive(cs);
  702. }
  703. }
  704. /// <summary>
  705. /// 服务接收异常
  706. /// </summary>
  707. /// <param name="rs"></param>
  708. /// <param name="ex">异常信息</param>
  709. /// <param name="restart">异常信息</param>
  710. protected virtual void OnReceiveException(ReceiveSession rs, Exception ex, bool restart = false)
  711. {
  712. if (restart)
  713. {
  714. // 重启接收
  715. StartReceive(rs.Client);
  716. ServerMessageEventArgs e = new ServerMessageEventArgs
  717. {
  718. Type = ServerMessageType.Error,
  719. Code = "CNS-E-004",
  720. Message = $"服务端接收异常,重启客户端 {rs.Client} 连接",
  721. Exception = ex,
  722. Client = rs.Client,
  723. Server = rs.Client.Server
  724. };
  725. this.OnServerMessage(e);
  726. }
  727. else
  728. {
  729. ServerMessageEventArgs e = new ServerMessageEventArgs
  730. {
  731. Type = ServerMessageType.Error,
  732. Code = "CNS-E-005",
  733. Message = $"服务端接收异常,关闭客户端 {rs.Client} 连接",
  734. Exception = ex,
  735. Client = rs.Client,
  736. Server = rs.Client.Server
  737. };
  738. CloseClientSocket(rs);
  739. this.OnServerMessage(e);
  740. }
  741. }
  742. /// <summary>
  743. /// 客户端下线
  744. /// </summary>
  745. /// <param name="rs"></param>
  746. /// <param name="ex"></param>
  747. protected virtual void OnClientDown(ReceiveSession rs, Exception ex = null)
  748. {
  749. //Framework.Log.Logger.Debug("OnClientDown", "timeout");
  750. ServerMessageEventArgs e = new ServerMessageEventArgs
  751. {
  752. Type = ServerMessageType.Trace,
  753. Client = rs.Client,
  754. Server = rs.Client.Server
  755. };
  756. if (ex == null)
  757. {
  758. e.Code = "CNS-T-003";
  759. e.Message = $"客户端 {rs.Client} 已下线";
  760. }
  761. else
  762. {
  763. e.Code = "CNS-T-004";
  764. e.Message = $"客户端 {rs.Client} 已下线(异常)";
  765. e.Exception = ex;
  766. }
  767. CloseClientSocket(rs);
  768. this.OnServerMessage(e);
  769. }
  770. private void CloseClientSocket(ClientSession cs)
  771. {
  772. cs?.Socket?.Close();
  773. cs?.Clear();
  774. clients.Remove(cs.ID);
  775. }
  776. private void CloseClientSocket(ReceiveSession rs)
  777. {
  778. CloseClientSocket(rs.Client);
  779. }
  780. /// <summary>
  781. /// 客户端发送超时
  782. /// </summary>
  783. /// <param name="rs"></param>
  784. protected virtual void OnClientTimeout(ReceiveSession rs)
  785. {
  786. ServerMessageEventArgs e = new ServerMessageEventArgs
  787. {
  788. Type = ServerMessageType.Trace,
  789. Code = "CNS-T-005",
  790. Message = $"客户端 {rs.Client} 发送超时",
  791. Client = rs.Client,
  792. Server = rs.Client.Server
  793. };
  794. this.OnServerMessage(e);
  795. }
  796. /// <summary>
  797. /// 服务接收超时
  798. /// </summary>
  799. /// <param name="rs"></param>
  800. /// <param name="isHead"></param>
  801. protected virtual void OnReceiveTimeout(ReceiveSession rs, bool isHead)
  802. {
  803. ServerMessageEventArgs e = new ServerMessageEventArgs
  804. {
  805. Type = ServerMessageType.Trace,
  806. Code = "CNS-T-006",
  807. Message = $"接收客户端 {rs.Client} {(isHead ? "报文头" : "报文内容")}超时",
  808. Client = rs.Client,
  809. Server = rs.Client.Server
  810. };
  811. //StartReceive(rs.Client);
  812. CloseClientSocket(rs);
  813. this.OnServerMessage(e);
  814. }
  815. /// <summary>
  816. /// 服务端异常下线
  817. /// </summary>
  818. /// <param name="ss"></param>
  819. /// <param name="ex"></param>
  820. protected virtual void OnServerDownError(ServerSession ss, Exception ex)
  821. {
  822. ServerMessageEventArgs e = new ServerMessageEventArgs
  823. {
  824. Type = ServerMessageType.Debug,
  825. Code = "CNS-D-000",
  826. Message = "服务端已关闭",
  827. Exception = ex,
  828. Server = ss
  829. };
  830. this.OnServerMessage(e);
  831. }
  832. /// <summary>
  833. /// 回复消息
  834. /// </summary>
  835. /// <param name="rs"></param>
  836. /// <param name="message"></param>
  837. protected internal virtual void ReturnMessage(ReceiveSession rs, string message)
  838. {
  839. //Framework.Log.Logger.Debug("SetMessage", "timeout");
  840. if (rs.Client == null || rs.Client.Socket == null)
  841. {
  842. // TO Message?
  843. return;
  844. }
  845. byte[] bs = Model.ToSendFromCommand(message);
  846. if (bs != null && bs.Length > 0)
  847. {
  848. try
  849. {
  850. rs.Client.Socket.SendTimeout = this.SendTimeout;
  851. rs.Client.Socket.Send(bs);
  852. }
  853. //catch (ObjectDisposedException ex)
  854. //{
  855. // // 客户端Socket已关闭(接收超时)
  856. // //OnReceiveTimeout(rs);
  857. // // 服务已停止
  858. // //OnServerDownError(rs.Client.Server, ex);
  859. // return;
  860. //}
  861. catch (SocketException ex)
  862. {
  863. ServerMessageEventArgs e = new ServerMessageEventArgs
  864. {
  865. Type = ServerMessageType.Trace,
  866. Code = "CNS-T-007",
  867. Message = $"发送客户端 {rs.Client} [{message}] 超时",
  868. Client = rs.Client,
  869. Server = rs.Client?.Server,
  870. Exception = ex
  871. };
  872. this.OnServerMessage(e);
  873. }
  874. catch (Exception ex)
  875. {
  876. ServerMessageEventArgs e = new ServerMessageEventArgs
  877. {
  878. Type = ServerMessageType.Trace,
  879. Code = "CNS-T-008",
  880. Message = $"发送客户端 {rs.Client} [{message}] 异常",
  881. Client = rs.Client,
  882. Server = rs.Client?.Server,
  883. Exception = ex
  884. };
  885. this.OnServerMessage(e);
  886. }
  887. }
  888. }
  889. #endregion
  890. #region Start & Stop
  891. /// <summary>
  892. /// 启动服务
  893. /// </summary>
  894. /// <param name="port">端口号</param>
  895. public virtual void Start(int port)
  896. {
  897. Start(port, null);
  898. }
  899. /// <summary>
  900. /// 启动服务
  901. /// </summary>
  902. /// <param name="port">端口号</param>
  903. /// <param name="backlog">挂起连接队列的最大长度</param>
  904. public virtual void Start(int port, int backlog)
  905. {
  906. Start(port, null, backlog);
  907. }
  908. /// <summary>
  909. /// 启动服务
  910. /// </summary>
  911. /// <param name="port">端口号</param>
  912. /// <param name="ipAddress">IP地址</param>
  913. /// <param name="backlog">挂起连接队列的最大长度</param>
  914. public virtual void Start(int port, IPAddress ipAddress, int backlog = 100)
  915. {
  916. if (!Started)
  917. {
  918. CancelEventArgs e = new CancelEventArgs();
  919. this.OnServerStarting(e);
  920. if (e.Cancel)
  921. {
  922. return;
  923. }
  924. IPEndPoint ipEndPoint = new IPEndPoint(ipAddress ?? IPAddress.Any, port);
  925. ServerSession ss = new ServerSession
  926. {
  927. IPEndPoint = ipEndPoint,
  928. Backlog = backlog,
  929. };
  930. this.CreateSocket();
  931. //this.Socket.ReceiveTimeout = this.ReceiveTimeout;
  932. this.Socket.Bind(ipEndPoint);
  933. this.Socket.Listen(ss.Backlog);
  934. ss.Socket = this.Socket;
  935. //AcceptResult = this.Socket.BeginAccept(new AsyncCallback(AcceptCallback), ss);
  936. this.Socket.BeginAccept(new AsyncCallback(AcceptCallback), ss);
  937. this.Started = true;
  938. this.ServerSession = ss;
  939. this.OnServerStarted(EventArgs.Empty);
  940. }
  941. }
  942. //IAsyncResult AcceptResult = null;
  943. /// <summary>
  944. /// 关闭服务器的引擎
  945. /// </summary>
  946. public virtual void Stop()
  947. {
  948. if (Started)
  949. {
  950. CancelEventArgs e = new CancelEventArgs();
  951. this.OnServerStoping(e);
  952. if (e.Cancel)
  953. {
  954. return;
  955. }
  956. this.StopCore();
  957. }
  958. }
  959. /// <summary>
  960. /// 停止服务
  961. /// </summary>
  962. protected virtual void StopCore()
  963. {
  964. this.ServerSession?.Clear();
  965. this.ServerSession = null;
  966. this.Started = false;
  967. this.Close();
  968. this.Socket = null;
  969. //this.Socket.EndAccept(AcceptResult);
  970. foreach (ClientSession item in clients.Values)
  971. {
  972. item.Socket?.Close();
  973. item.Clear();
  974. }
  975. clients.Clear();
  976. this.OnServerStoped(EventArgs.Empty);
  977. }
  978. /// <summary>
  979. /// 销毁
  980. /// </summary>
  981. public override void Dispose()
  982. {
  983. try
  984. {
  985. this.StopCore();
  986. }
  987. catch
  988. {
  989. }
  990. base.Dispose();
  991. }
  992. #endregion
  993. }
  994. /// <summary>
  995. /// Socket 服务端
  996. /// </summary>
  997. public class SocketServer<TServerModel> : SocketServer
  998. where TServerModel : IServerModel, new()
  999. {
  1000. #region 属性
  1001. /// <summary>
  1002. /// 服务端模型
  1003. /// </summary>
  1004. public override IServerModel Model
  1005. {
  1006. get
  1007. {
  1008. return this.ServerModel as IServerModel;
  1009. }
  1010. }
  1011. /// <summary>
  1012. /// 服务端模型
  1013. /// </summary>
  1014. public TServerModel ServerModel
  1015. {
  1016. get; protected set;
  1017. }
  1018. #endregion
  1019. #region 构造
  1020. /// <summary>
  1021. /// Socket 服务端
  1022. /// </summary>
  1023. public SocketServer(bool newModel = false)
  1024. {
  1025. if (newModel)
  1026. {
  1027. ServerModel = new TServerModel();
  1028. }
  1029. else
  1030. {
  1031. ServerModel = PLC.Model.ServerModel.CreateModel<TServerModel>();
  1032. }
  1033. this.ReceiveTimeout = this.ServerModel.ReceiveTimeout;
  1034. this.SendTimeout = this.ServerModel.SendTimeout;
  1035. }
  1036. /// <summary>
  1037. /// Socket 服务端
  1038. /// </summary>
  1039. /// <param name="model">新实例</param>
  1040. public SocketServer(TServerModel model)
  1041. {
  1042. if (model == null)
  1043. {
  1044. throw new NullReferenceException("ServerSocket TServerModel");
  1045. }
  1046. ServerModel = model;
  1047. this.ReceiveTimeout = this.ServerModel.ReceiveTimeout;
  1048. this.SendTimeout = this.ServerModel.SendTimeout;
  1049. }
  1050. #endregion
  1051. }
  1052. }