using Polly; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using DM_Weight.Models; using DM_Weight.ViewModels; using log4net; namespace DM_Weight.Port { public class KeepAliveSocket { /// /// 生成带有心跳检测的socket /// public class KeepALiveSocket { private static ILog socketLogger = LogManager.GetLogger(typeof(CheckOrderNewWindowViewModel)); public static Socket MakeKeepALiveSocket(string ip, int port) { uint dummy = 0; byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3]; BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);//启用Keep-Alive BitConverter.GetBytes((uint)10000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));//在这个时间间隔内没有数据交互,则发送探测包 BitConverter.GetBytes((uint)10000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);//发探测包时间间隔 IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ip), port); Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket = Policy.Handle() .Retry(3, (exception, retryCount) => { socketLogger.Info($"建立Socket,第{retryCount}次重试", exception); // return TimeSpan.FromSeconds (1); }) .Execute(() => { _socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); _socket.Connect(iep); return _socket; }); return _socket; } public static Socket MakeKeepALiveSocket(IpAndPort ipAndPort) { uint dummy = 0; byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3]; BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);//启用Keep-Alive BitConverter.GetBytes((uint)10000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));//在这个时间间隔内没有数据交互,则发送探测包 BitConverter.GetBytes((uint)10000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);//发探测包时间间隔 IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ipAndPort.Ip), ipAndPort.Port); Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket = Policy.Handle() .Retry(3, (exception, retryCount) => { socketLogger.Info($"建立Socket,第{retryCount}次重试", exception); // return TimeSpan.FromSeconds (1); }) .Execute(() => { _socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); _socket.Connect(iep); return _socket; }); return _socket; } } } }