123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- namespace Utilities
- {
- public class SocketUtils
- {
- public static void SetKeepAlive(Socket socket, TimeSpan timeout)
- {
-
- SetKeepAlive(socket, true, timeout, TimeSpan.FromSeconds(1));
- }
-
-
- public static void SetKeepAlive(Socket socket, bool enable, TimeSpan timeout, TimeSpan interval)
- {
- socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
-
- byte[] tcp_keepalive = new byte[12];
- LittleEndianWriter.WriteUInt32(tcp_keepalive, 0, Convert.ToUInt32(enable));
- LittleEndianWriter.WriteUInt32(tcp_keepalive, 4, (uint)timeout.TotalMilliseconds);
- LittleEndianWriter.WriteUInt32(tcp_keepalive, 8, (uint)interval.TotalMilliseconds);
- socket.IOControl(IOControlCode.KeepAliveValues, tcp_keepalive, null);
- }
-
-
-
- public static void ReleaseSocket(Socket socket)
- {
- if (socket != null)
- {
- if (socket.Connected)
- {
- try
- {
- socket.Shutdown(SocketShutdown.Both);
- socket.Disconnect(false);
- }
- catch (ObjectDisposedException)
- {
- return;
- }
- catch (SocketException)
- {
- }
- }
-
- socket.Close();
- }
- }
- }
- }
|