NetUdpClient.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. namespace HslCommunication.Enthernet
  8. {
  9. /// <summary>
  10. /// UDP客户端的类,只负责发送数据到服务器,该数据经过封装
  11. /// </summary>
  12. public class NetUdpClient : Core.Net.NetworkBase
  13. {
  14. private IPEndPoint ServerEndPoint = null;
  15. /// <summary>
  16. /// 实例化对象,
  17. /// </summary>
  18. /// <param name="endpoint"></param>
  19. public NetUdpClient( IPEndPoint endpoint )
  20. {
  21. ServerEndPoint = endpoint;
  22. CoreSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp );
  23. }
  24. /// <summary>
  25. /// 实例化对象,指定发送的服务器地址和端口号
  26. /// </summary>
  27. /// <param name="ipAddress">服务器的Ip地址</param>
  28. /// <param name="port">端口号</param>
  29. public NetUdpClient( string ipAddress,int port )
  30. {
  31. ServerEndPoint = new IPEndPoint( IPAddress.Parse( ipAddress ), port );
  32. CoreSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp );
  33. }
  34. /// <summary>
  35. /// 发送字节数据到服务器
  36. /// </summary>
  37. /// <param name="customer">用户自定义的标记数据</param>
  38. /// <param name="data">字节数据</param>
  39. /// <exception cref="ArgumentNullException"></exception>
  40. /// <exception cref="SocketException"></exception>
  41. /// <exception cref="ObjectDisposedException"></exception>
  42. public void SendMessage( NetHandle customer, byte[] data )
  43. {
  44. CoreSocket.SendTo( HslProtocol.CommandBytes( customer, Token, data ), ServerEndPoint );
  45. }
  46. /// <summary>
  47. /// 发送字符串数据到服务器
  48. /// </summary>
  49. /// <param name="customer">用户自定义的标记数据</param>
  50. /// <param name="data">字符串数据</param>
  51. /// <exception cref="ArgumentNullException"></exception>
  52. /// <exception cref="SocketException"></exception>
  53. /// <exception cref="ObjectDisposedException"></exception>
  54. public void SendMessage( NetHandle customer, string data )
  55. {
  56. CoreSocket.SendTo( HslProtocol.CommandBytes( customer, Token, data ), ServerEndPoint );
  57. }
  58. #region Object Override
  59. /// <summary>
  60. /// 获取本对象的字符串表示形式
  61. /// </summary>
  62. /// <returns></returns>
  63. public override string ToString( )
  64. {
  65. return "NetUdpClient";
  66. }
  67. #endregion
  68. }
  69. }