“WCF服务连接丢失”问题及解决

一  现象

在“输出-调试”窗口外输出如下异常信息

System.ServiceModel.CommunicationException: 套接字连接已中止。这可能是由于处理消息时出错或远程主机超过接收超时或者潜在的网络资源问题导致的。本地套接字超时是“10675199.02:48:05.4775807”。 ---> System.Net.Sockets.SocketException: 远程主机强迫关闭了一个现有的连接。
   --- 内部异常堆栈跟踪的结尾 ---
   在 System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
   在 System.ServiceModel.Channels.FramingDuplexSessionChannel.EndTryReceive(IAsyncResult result, Message& message)
   在 System.ServiceModel.Dispatcher.DuplexChannelBinder.EndTryReceive(IAsyncResult result, RequestContext& requestContext)
   在 System.ServiceModel.Dispatcher.ErrorHandlingReceiver.EndTryReceive(IAsyncResult result, RequestContext& requestContext)




二  服务器端异常捕捉方式

服务器端的IContextChannel(OperationContext.Current.Channel).Faulted事件




三  原因分析及解决

原因1:消息包长度受限

解决:加长长度,参考http://www.cnblogs.com/snowsky/archive/2010/12/22/1913601.html

示例:

服务端配置:

<basicHttpBinding>
	<binding name="basicBinding" maxReceivedMessageSize="2147483647"></binding>
</basicHttpBinding>
<behavior name="bcf">
	<serviceMetadata httpGetEnabled="true" />
	<serviceDebug includeExceptionDetailInFaults="false" />
	<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</serviceBehaviors>


客户端配置:

<behaviors>
	<endpointBehaviors>
		<behavior name="bhc">
			<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
		</behavior>
	</endpointBehaviors>
</behaviors>
<basicHttpBinding>
	<binding name="basicBinding" maxReceivedMessageSize="2147483647"></binding>
</basicHttpBinding>




原因2、客户端创建使用完服务代理后未回收此资源

解决:回收

示例:

using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(new WSHttpBinding(), "http://127.0.0.1:9999/calculatorservice"))
{
	ICalculator proxy = channelFactory.CreateChannel();
	using (proxy as IDisposable)
	{
	    //哒哒哒...
	}
}


勉強心を持てば、生活は虚しくない!
原文地址:https://www.cnblogs.com/beta2013/p/3377305.html