[WCF] Разрыв соединения сервером без объяснения причин и рек
От: Interceptor Украина  
Дата: 26.10.09 14:07
Оценка:
Добрый день,

недавно я столкнулся с мистицизмом, а именно WCF сервис (тестируемый локально), в котором включены все возможные логи не выдавал никаких ошибок, тем не менее, клиент (nunit fixture) сообщает о том, сервер разорвал соединение

System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to http://localhost:8000/My.WCF.Services/Admin/. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(ref MessageData msgData, Int32 type)


Думаю, что проблема не нова, так как ей пестрит интернет. Есть много решений:
1) включение логов
            MyServiceHost<Admin> adminHost = new MyServiceHost<Admin>();
            try
            {
                adminHost.Open();
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.ReadLine();
                adminHost.Close();
            }
                        catch (CommunicationException ce)
            {
                Console.WriteLine("Communication exception occurred: {0}", ce.Message);
            } 
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred: {0}", ex.Message);
            } 
            finally
            {
                adminHost.Abort();
                userHost.Abort();
            }


  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="messages"
          type="System.Diagnostics.XmlWriterTraceListener"
          initializeData="wcf_messages.xml" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>


  <system.serviceModel>
    <diagnostics>
      <messageLogging
           logEntireMessage="true"
           logMalformedMessages="false"
           logMessagesAtServiceLevel="true"
           logMessagesAtTransportLevel="false"
           maxMessagesToLog="3000"
           maxSizeOfMessageToLog="2000"/>
    </diagnostics>

2) увеличение буфера:
    <bindings>
      <wsHttpBinding>
        <binding name="WSNoSecurityBinding" maxBufferPoolSize="2097152"
          maxReceivedMessageSize="2097152">
          <security mode="None">
            <transport clientCredentialType="None">
              <extendedProtectionPolicy policyEnforcement="Never" />
            </transport>
            <message establishSecurityContext="false" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>

3) увеличение таймаута
<binding name="WSHttpBinding_IAdmin" closeTimeout="00:02:00"
                    openTimeout="00:02:00" receiveTimeout="00:20:00" sendTimeout="00:05:00"
                    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="16777216" maxReceivedMessageSize="8388608"
                    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies="false">
                    <readerQuotas maxDepth="64" maxStringContentLength="16384" maxArrayLength="32768"
                        maxBytesPerRead="16384" maxNameTableCharCount="32768" />
                    <reliableSession ordered="true" inactivityTimeout="00:20:00"
                        enabled="false" />
                    <security mode="None">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="">
                            <extendedProtectionPolicy policyEnforcement="Never" />
                        </transport>
                        <message clientCredentialType="Windows" negotiateServiceCredential="true"
                            establishSecurityContext="true" />
                    </security>
                </binding>


но все эти способы не годятся в том случае, если речь идет о передачи рекурсивных данных, к примеру экземпляра класса Class1
    [DataContract]
    public class Class1
    {
        public Class1(string text,int count)
        {
            Childs = new List<Class2>();
            for(int i =0;i<count;i++)
            {
                Childs.Add(new Class2(this,text + i.ToString()));
            }
            Text = text;
        }

        [DataMember]
        public IList<Class2> Childs { get; set; }
        [DataMember]
        public string Text { get; set; }
    }
    
    [DataContract]
    public class Class2
    {
        public Class2(Class1 parent,string text)
        {
            Parent = parent;
            Text = text;
        }
        [DataMember]
        public Class1 Parent { get; set; }
        [DataMember]
        public string Text { get; set; }
    }

В этом случае весь буфер все равно забирается (возможно поможет игра с параметрами readerQuotas, но не уверен).

Единственный способ избежать ошибки, как мне видится — убрать рекурсивное обращение из Class2 к Parent (Class1).
... << RSDN@Home 1.2.0 alpha 4 rev. 1138>>
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.