gpt4 book ai didi

C# 检查套接字是否断开?

转载 作者:太空狗 更新时间:2023-10-29 21:41:42 26 4
gpt4 key购买 nike

如何在不使用 Poll 的情况下检查非阻塞套接字是否断开连接?

最佳答案

创建一个继承 .net 套接字类的自定义套接字类:

public delegate void SocketEventHandler(Socket socket);
public class CustomSocket : Socket
{
private readonly Timer timer;
private const int INTERVAL = 1000;

public CustomSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
: base(addressFamily, socketType, protocolType)
{
timer = new Timer { Interval = INTERVAL };
timer.Tick += TimerTick;
}

public CustomSocket(SocketInformation socketInformation)
: base(socketInformation)
{
timer = new Timer { Interval = INTERVAL };
timer.Tick += TimerTick;
}

private readonly List<SocketEventHandler> onCloseHandlers = new List<SocketEventHandler>();
public event SocketEventHandler SocketClosed
{
add { onCloseHandlers.Add(value); }
remove { onCloseHandlers.Remove(value); }
}

public bool EventsEnabled
{
set
{
if(value)
timer.Start();
else
timer.Stop();
}
}

private void TimerTick(object sender, EventArgs e)
{
if (!Connected)
{
foreach (var socketEventHandler in onCloseHandlers)
socketEventHandler.Invoke(this);
EventsEnabled = false;
}
}

// Hiding base connected property
public new bool Connected
{
get
{
bool part1 = Poll(1000, SelectMode.SelectRead);
bool part2 = (Available == 0);
if (part1 & part2)
return false;
else
return true;
}
}
}

然后像这样使用它:

        var socket = new CustomSocket(
//parameters
);

socket.SocketClosed += socket_SocketClosed;
socket.EventsEnabled = true;


void socket_SocketClosed(Socket socket)
{
// do what you want
}

我刚刚在每个套接字中实现了一个套接字关闭事件。所以您的应用程序应该为此事件注册事件处理程序。然后套接字将通知您的应用程序,如果它自己关闭了;)

如果代码有任何问题,请告诉我。

关于C# 检查套接字是否断开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5698421/

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