SocketEx.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Net.Sockets;
  3. namespace SuperSocket.Common
  4. {
  5. /// <summary>
  6. /// Socket extension class
  7. /// </summary>
  8. public static class SocketEx
  9. {
  10. /// <summary>
  11. /// Close the socket safely.
  12. /// </summary>
  13. /// <param name="socket">The socket.</param>
  14. public static void SafeClose(this Socket socket)
  15. {
  16. if (socket == null)
  17. return;
  18. if (!socket.Connected)
  19. return;
  20. try
  21. {
  22. socket.Shutdown(SocketShutdown.Both);
  23. }
  24. catch
  25. {
  26. }
  27. try
  28. {
  29. socket.Close();
  30. }
  31. catch
  32. {
  33. }
  34. }
  35. /// <summary>
  36. /// Sends the data.
  37. /// </summary>
  38. /// <param name="client">The client.</param>
  39. /// <param name="data">The data.</param>
  40. public static void SendData(this Socket client, byte[] data)
  41. {
  42. SendData(client, data, 0, data.Length);
  43. }
  44. /// <summary>
  45. /// Sends the data.
  46. /// </summary>
  47. /// <param name="client">The client.</param>
  48. /// <param name="data">The data.</param>
  49. /// <param name="offset">The offset.</param>
  50. /// <param name="length">The length.</param>
  51. public static void SendData(this Socket client, byte[] data, int offset, int length)
  52. {
  53. int sent = 0;
  54. int thisSent = 0;
  55. while ((length - sent) > 0)
  56. {
  57. thisSent = client.Send(data, offset + sent, length - sent, SocketFlags.None);
  58. sent += thisSent;
  59. }
  60. }
  61. }
  62. }