UdpSocket.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 
  2. using System;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. namespace IFramework.Net.Udp
  6. {
  7. internal class UdpSocket
  8. {
  9. internal Socket socket = null;
  10. internal bool Broadcast = false;
  11. protected bool isConnected = false;
  12. protected EndPoint ipEndPoint = null;
  13. protected byte[] receiveBuffer = null;
  14. protected int receiveChunkSize = 4096;
  15. protected int receiveTimeout = 1000 * 60 * 30;
  16. protected int sendTimeout = 1000 * 60 * 30;
  17. public UdpSocket(int size,bool Broadcast=false)
  18. {
  19. this.receiveChunkSize = size;
  20. this.receiveBuffer = new byte[size];
  21. this.Broadcast = Broadcast;
  22. }
  23. protected void SafeClose()
  24. {
  25. if (socket == null) return;
  26. if (socket.Connected)
  27. {
  28. try
  29. {
  30. socket.Disconnect(true);
  31. socket.Shutdown(SocketShutdown.Send);
  32. }
  33. catch (ObjectDisposedException)
  34. {
  35. return;
  36. }
  37. catch
  38. { }
  39. }
  40. try
  41. {
  42. socket.Close();
  43. socket.Dispose();
  44. }
  45. catch
  46. { }
  47. }
  48. public void CreateUdpSocket(int port, IPAddress ip)
  49. {
  50. if (Broadcast) ipEndPoint = new IPEndPoint(IPAddress.Broadcast, port);
  51. else ipEndPoint = new IPEndPoint(ip, port);
  52. socket = new Socket(ipEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
  53. {
  54. ReceiveTimeout = receiveTimeout,
  55. SendTimeout = sendTimeout
  56. };
  57. #if UDP_SOCKET_OPTION
  58. //https://docs.microsoft.com/zh-cn/dotnet/api/system.net.sockets.socket.setsocketoption?redirectedfrom=MSDN&view=netframework-4.7.2
  59. if (Broadcast)
  60. {
  61. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  62. }
  63. else
  64. socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IPOptions, true);
  65. #endif
  66. }
  67. }
  68. }