SocketUtils.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /* Copyright (C) 2012-2015 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.Text;
  12. namespace Utilities
  13. {
  14. public class SocketUtils
  15. {
  16. /// <summary>
  17. /// Socket will be forcefully closed, all pending data will be ignored, and socket will be deallocated.
  18. /// </summary>
  19. public static void ReleaseSocket(Socket socket)
  20. {
  21. if (socket != null)
  22. {
  23. if (socket.Connected)
  24. {
  25. socket.Shutdown(SocketShutdown.Both);
  26. try
  27. {
  28. socket.Disconnect(false);
  29. }
  30. catch (ObjectDisposedException)
  31. {
  32. return;
  33. }
  34. catch (SocketException)
  35. { }
  36. }
  37. socket.Close();
  38. socket = null;
  39. GC.Collect();
  40. GC.WaitForPendingFinalizers();
  41. }
  42. }
  43. }
  44. }