Bootstrap

当WCF遭遇An existing connection was forcibly closed by the remote host

昨天,在博客园个人主页招聘页面遇到一个奇怪的WCF问题,错误信息如下:

An existing connection was forcibly closed by the remote host

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Stack Trace:

[SocketException (0x2746): An existing connection was forcibly closed by the remote host] 
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +232
[IOException: Unable to read data from the transport connection:
An existing connection was forcibly closed by the remote host.]
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +7035903
System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) +20
System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead) +435
[WebException: The underlying connection was closed:
A connection that was expected to be kept alive was closed by the server.]
System.Net.HttpWebRequest.GetResponse() +1126
System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +81
[CommunicationException: The underlying connection was closed:
A connection that was expected to be kept alive was closed by the server.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +10259418
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +539

这个页面的职位信息是通过调用招聘频道的WCF服务获取的。

一开始以为是WCF的配置问题,检查之后没发现问题。

在开发机器上测试,没有出现这个问题,开发机器与服务器的主要差别就是职位信息数据不一样,问题可能出在WCF客户端与服务器之间传递的职位信息数据,于是将解决问题的焦点锁定于此。

该WCF服务返回的是职位信息列表-List<JobOfferInfo>,JobOfferInfo包含有企业信息-EnterpriseInfo。

为了找到哪个属性值引起这个问题,对返回的职位信息列表,我们逐个地将JobOfferInfo的属性设置为空值并测试...

终于发现是EnterpriseInfo的一个枚举属性值引起的,该枚举属性是CompanySize,枚举类型定义是:

    [Flags()]
    
public   enum  CompanySize
    {
        NoSet 
=   0 ,
        Micro 
=   1 ,
        Small 
=   2 ,
        Medium 
=   4 ,
        Big 
=   8 ,     
        Giant 
=   16
    }

当这个属性值是-1时,就会引发WCF出现"An existing connection was forcibly closed by the remote host"错误。

当然, CompanySize的值不应该出现-1,这是一个Bug引起的,但WCF的这个错误信息实在让人费解。

;