在WCF中检测套接字断开连接
我们正在构建一个WCF服务器(.NET 4.0)。它只会使用net.tcp传输。在WCF中检测套接字断开连接
当客户端关闭TCP连接时,服务器得到未处理的CommunicationException并终止。
Q1。如何处理CommunicationException,以便服务器不终止并继续为其他客户端服务? Q2302。在处理程序中,如何获取已中止的会话的SessionId?我需要这个来清理一些会话特定的数据。
在此先感谢!
P.S.连接通过互联网,因此无论客户端是否优雅地断开连接,套接字都可以随时关闭。
任何WCF通道都实现了ICommunicationObject,它提供了通道寿命的事件。
你应该听Faulted事件
的SessionID可以一如既往从OperationContext.Current属性访问。
当你的客户端中打开通道(第一操作),注册到适当的事件:
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;
}
[...]
}
仅当客户端正常关闭时才有效。当套接字突然断开时它不起作用。 – Soonts 2011-03-17 12:33:48
如果套接字断开,你应该得到一个通道故障事件。当客户端正常关闭时触发闭合事件,当意外情况发生时触发Faulted(如出现网络故障)。 – Eilistraee 2011-03-17 13:52:39
当transferMode =“Streamed”时,这些不起作用 – gordy 2015-02-03 08:08:17
ICommunicationObject obj = (ICommunicationObject)callback;
obj.Closed += new EventHandler((a, b) =>
{
if (list.Exists(cli => cli.CallbackService == (ITecnobelRemoteServiceCallback)a))
{
var query = (from cc in list where cc.CallbackService == (ITecnobelRemoteServiceCallback)a select cc).ToList();
query.ForEach(
delegate (Client ccc)
{
ccc.CallbackService = null;
});
}
});
什么类,你正在使用的?你用什么方法读取和写入类?有几个类用于处理TCP连接。仅举几例,'Socket','TcpClient' – 2011-03-17 12:18:51
这些套接字隐藏在WCF框架的深处。在某些客户端中,我使用System.ServiceModel.ChannelFactory泛型类连接到服务器。 –
Soonts
2011-03-17 12:40:40