gpt4 book ai didi

sockets - Socket.IOControl dotnet 核心 Linux 不工作

转载 作者:行者123 更新时间:2023-12-03 11:51:04 26 4
gpt4 key购买 nike

我目前正在使用 Socket.IOControl 使用 keepalive 的服务器上工作但它不适用于 dotnet core Linux当我尝试运行它时,我得到一个 PlatformNotSupportedException

在 dotnet core 中实现 keepalive 是否有跨平台的替代方案?

示例测试代码

private static void Main(string[] args)
{
Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
socket.Bind((EndPoint)new IPEndPoint(IPAddress.Loopback, 3178));
socket.Listen(10);
Console.WriteLine("Server: Begin Listening");
socket.BeginAccept(new AsyncCallback(Program.AcceptCallback), (object)socket);
Console.WriteLine("Client: Begin Connecting");
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(new IPEndPoint(IPAddress.Loopback, 3178));
Console.WriteLine("Client: Connected");
Console.WriteLine("Client: Client keepAlive");
Program.SetSocketKeepAliveValues(tcpClient.Client, 1000, 1);
Thread.Sleep(50);
Console.WriteLine("Done");
Console.ReadLine();
}

private static void AcceptCallback(IAsyncResult ar)
{
Socket asyncState = ar.AsyncState as Socket;
try
{
Socket socket = asyncState.EndAccept(ar);
Console.WriteLine("Server: Connection made");
Console.WriteLine("Server: Set keepAlive");
Program.SetSocketKeepAliveValues(socket, 1000, 1);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

public static void SetSocketKeepAliveValues(Socket socket, int KeepAliveTime, int KeepAliveInterval)
{
uint structure = 0;
byte[] optionInValue = new byte[Marshal.SizeOf<uint>(structure) * 3];
BitConverter.GetBytes(true ? 1U : 0U).CopyTo((Array)optionInValue, 0);
BitConverter.GetBytes((uint)KeepAliveTime).CopyTo((Array)optionInValue, Marshal.SizeOf<uint>(structure));
BitConverter.GetBytes((uint)KeepAliveInterval).CopyTo((Array)optionInValue, Marshal.SizeOf<uint>(structure) * 2);
socket.IOControl(IOControlCode.KeepAliveValues, optionInValue, (byte[])null);
}

提前致谢

最佳答案

基于此https://github.com/kburtram/corefx/commit/10791b0f6040e206887906a748fd119a16c6c2b9

您可以使用 SetSocketOption

设置 KeepAlive
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
this.socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 5);
this.socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 16);

关于sockets - Socket.IOControl dotnet 核心 Linux 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49781256/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com