IceUdpClient.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using CommonNetwork_ICE.Common;
  7. using Slice;
  8. using CommonNetwork_ICE.Util;
  9. using CommonNetwork_ICE.handler;
  10. using CommonLang.Protocol;
  11. using CommonNetwork_ICE.Msg;
  12. using CommonNetwork_ICE.Session;
  13. using CommonLang.Log;
  14. using CommonLang.Concurrent;
  15. namespace CommonNetwork_ICE.Client
  16. {
  17. /// <summary>
  18. /// ICE UDP客户端连接器,指定解码器,初始化本对象后可向指定服务器发送ICE消息,接收消息请先绑定会话侦听对象
  19. /// </summary>
  20. public class IceUdpClient : IceClientConnector
  21. {
  22. private static Logger log = LoggerFactory.GetLogger("IceUdpClient");
  23. public IceUdpClient(IceClientNetSession session)
  24. : this(session, Env.ICE_SEND_REMOTE_IP.Clone().ToString(), Env.ICE_SEND_REMOTE_PORT)
  25. {
  26. }
  27. public IceUdpClient(IceClientNetSession session, String ip, int port) : base(session, ip, port)
  28. {
  29. messageQueue = new ClientMessageQueue();
  30. }
  31. internal override SenderDisp_ getClientSendHandler(IceClientNetSession session, IceMessageCodec Codec)
  32. {
  33. ClientMsgHandlerUdpDelegate msgDelegate = new ClientMsgHandlerUdpDelegate(this, session);
  34. msgDelegate.Codec = Codec;
  35. return new ClientUdpSendHandler(msgDelegate);
  36. }
  37. /// <summary>
  38. /// 初始化ICE接收和发送端
  39. /// </summary>
  40. public override void Open(int localListenPort)
  41. {
  42. setLocalPort(localListenPort);
  43. this.ConnectToSever(Constants.COMM_TYPE_UDP);
  44. if (IsConnected)
  45. {
  46. messageQueue.Connector = Connector;
  47. messageQueue.Start();
  48. }
  49. }
  50. /// <summary>
  51. /// 关闭通讯通道
  52. /// </summary>
  53. public override void Close()
  54. {
  55. session.onClose();
  56. if (IsConnected)
  57. {
  58. messageQueue.End();
  59. CloseConnect();
  60. }
  61. }
  62. /// <summary>
  63. /// 具体的发送方法
  64. /// </summary>
  65. /// <param name="transMessage"></param>
  66. internal override bool SendTo(TransMessage transMessage)
  67. {
  68. if (transMessage.type == Constants.PACKET_HINGE)
  69. {
  70. messageQueue.AddMessage(transMessage);
  71. }
  72. else
  73. {
  74. try
  75. {
  76. Connector.Sender.SendData(this.Connector.GetConnectorConfig().LocalPort, transMessage);
  77. }
  78. catch (Exception e)
  79. {
  80. session.onException(e);
  81. return false;
  82. }
  83. }
  84. return true;
  85. }
  86. }
  87. }