gpt4 book ai didi

c# - 检测 WCF 中的套接字断开连接

转载 作者:可可西里 更新时间:2023-11-01 03:08:46 26 4
gpt4 key购买 nike

我们正在构建 WCF 服务器 (.NET 4.0)。它只会使用 net.tcp 传输。

当客户端关闭 TCP 连接时,服务器会收到未处理的 CommunicationException,并终止。

Q1。我如何处理 CommunicationException 以便服务器不会终止并继续为其他客户端提供服务?

Q2。在处理程序中,如何获取已中止 session 的 SessionId?我需要它来清理一些特定于 session 的数据。

提前致谢!

附言连接是通过 Internet 进行的,因此无论客户端是否正常断开连接,套接字都可能随时关闭。

最佳答案

任何 WCF channel 实现 ICommunicationObject ,它提供 channel 生命周期的事件。

你应该听Faulted事件

可以一如既往地从 OperationContext.Current 访问 sessionId属性(property)。

当您的客户端打开 channel 时(在第一次操作时),注册足够的事件:

OperationContext.Current.Channel.Faulted += new EventHandler(Channel_Faulted);
OperationContext.Current.Channel.Closed += new EventHandler(Channel_Faulted);

和:

 void Channel_Faulted(object sender, EventArgs e)
{
Logout((IContextChannel)sender);
}

protected void Logout(IContextChannel channel)
{
string sessionId = null;

if (channel != null)
{
sessionId = channel.SessionId;
}
[...]
}

关于c# - 检测 WCF 中的套接字断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5338842/

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