在WCF中使用流传输模式时发生超时错误 [英] Time out error when used streamed transfermode in wcf

查看:87
本文介绍了在WCF中使用流传输模式时发生超时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的wcf服务来下载和上传文件.
我的代码如下.

I am developing a simple wcf service to download and upload files.
My code is as below.

[MessageContract]
    public class FileUploadResult
    {
        [MessageHeader(MustUnderstand = true)]
        public Int64 Id { get; set; }

        [MessageHeader(MustUnderstand = true)]
        public Boolean IsSuccess { get; set; }

        [MessageHeader(MustUnderstand = true)]
        public String ErrorString { get; set; }


    }





[MessageContract]
    public class UploadFileData : IDisposable
    {
        [MessageHeader(MustUnderstand = true)]
        public Int64 TokenId { get; set; }

        [MessageHeader(MustUnderstand = true)]
        public String TokenKey { get; set; }

        [MessageHeader(MustUnderstand = true)]
        public Int64 Id { get; set; }

        [MessageHeader(MustUnderstand = true)]
        public Int64 UserId { get; set; }

        [MessageHeader(MustUnderstand = true)]
        public String Name { get; set; }

        [MessageHeader(MustUnderstand = true)]
        public String Desc { get; set; }

        [MessageHeader(MustUnderstand = true)]
        public Int64[] eveIds { get; set; }

        [MessageBodyMember(Order = 1)]
        public System.IO.Stream FileByteStream { get; set; }

        public void Dispose()
        {
            if (FileByteStream != null)
            {
                FileByteStream.Close();
                FileByteStream = null;
            }
        }
    }


服务界面就是这样


Service interface is like this

[ServiceContract]
    public interface ITest
    {
        [OperationContract]
        FileUploadResult UploadDocument(UploadFileData data);
       
    }



我的文件上传代码实现



My file upload code implementation

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, UseSynchronizationContext = false,ConcurrencyMode=ConcurrencyMode.Multiple)]
    public class Test : Interfaces.ITest
    {
        public FileUploadResult UploadDocument(UploadFileData data)
        {
            Stream sourceStream = null;
            FileStream targetStream = null;
            
            try
            {
                String filePath = @"C:\temp\" + data.Name;
                targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
                sourceStream = data.FileByteStream;
                
                const Int32 bufferLen = 1024;
                Byte[] buffer = new Byte[bufferLen];
                Int32 count = 0;
                while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                {
                    targetStream.Write(buffer, 0, count);
                }
               
                targetStream.Close();
                sourceStream.Close();

                FileUploadResult result = new FileUploadResult();
                result.ErrorString = "";
                result.IsSuccess = true;

                return result;
            }
            catch (Exception ex)
            {
                FileUploadResult result = new FileUploadResult();
                result.ErrorString = ex.Message;
                result.IsSuccess = false;

                return result;
            }
        }



我的服务app.config文件



My service app.config file

<basicHttpBinding><binding name="basicHTTPStreem" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="true" maxReceivedMessageSize="2147483647"

                 maxBufferPoolSize="2147483647" messageEncoding="Text" transferMode="Streamed" maxBufferSize="2147483647">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
          <security mode="None">
            <transport clientCredentialType="None"/>
          </security>
        </binding></basicHttpBinding>


<service behaviorConfiguration="serviceBehavior" name="Classes.Test">
        <endpoint address="http://serveraddress/Classes.test.svc"

          binding="basicHttpBinding" bindingConfiguration="basicHTTPStreem"

          name="HTTP_Classes.Test" contract="Interfaces.ITest">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://serveraddress/Classes.test.svc" />
          </baseAddresses>
        </host>
      </service>


我的Windows客户端应用程序代码如下.


My windows client application code as follows.

EndpointAddress address = new EndpointAddress("http://serveraddress/Classes.test.svc");
                BasicHttpBinding binding = new BasicHttpBinding("HTTP_Classes.Test");

                System.IO.Stream stream = new System.IO.FileStream("db_Empty.sql", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                Boolean isSuccess;
                Int64 Id = 0;

                CNTest.TestClient test = new CNTest.TestClient(binding, address);
                String ErrorString = test.UploadDocument("test", new Int64[] { 2 }, ref Id, "db_Empty.sql", 5, "3eee3", 5, stream, out isSuccess);

                    if (!isSuccess)
                    MessageBox.Show(ErrorString);



客户端app.config文件.



Client app.config file.

<basicHttpBinding>
<binding name="HTTP_Classes.Test" closeTimeout="00:01:00" openTimeout="00:01:00"

                          receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"

                          bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"

                          maxBufferSize="2147483647" maxBufferPoolSize="2147483647"

                          maxReceivedMessageSize="2147483647" messageEncoding="Text"

                          textEncoding="utf-8" transferMode="Streamed" useDefaultWebProxy="true">
                          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"

                                maxArrayLength="2147483647" maxBytesPerRead="2147483647"

                                maxNameTableCharCount="2147483647" />
                          <security mode="None">
                                <transport clientCredentialType="None" proxyCredentialType="None"

                                      realm="" />
                                <message clientCredentialType="UserName" algorithmSuite="Default" />
                          </security>
                    </binding>
</basicHttpBinding>
<endpoint address="http://serveraddress/Classes.Test.svc"

                    binding="basicHttpBinding" bindingConfiguration="HTTP_Classes.Test"

                    contract="CNTest.ITest" name="HTTP_Classes.Test" />



当我在客户端的配置文件中使用transferMode ="Buffered"时,以上代码可以正常工作,但是如果我使用transferMode ="Streamed",则出现此错误
套接字连接已中止.这可能是由于处理您的消息时出错或远程主机超出了接收超时,或者是潜在的网络资源问题.本地套接字超时为"00:00:59.9680000"."

堆栈跟踪为



The above code working fine when I used transferMode="Buffered" in client''s config file but if I use transferMode="Streamed" then I am getting this error
"The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was ''00:00:59.9680000''."

The Stack Trace is

Server stack trace: 
   at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.WebRequestOutputStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.BufferedStream.Write(Byte[] array, Int32 offset, Int32 count)
   at System.Xml.XmlStreamNodeWriter.FlushBuffer()
   at System.Xml.XmlUTF8NodeWriter.WriteBase64Text(Byte[] buffer, Int32 offset, Int32 count)
   at System.Xml.XmlUTF8NodeWriter.WriteBase64Text(Byte[] trailBytes, Int32 trailByteCount, Byte[] buffer, Int32 offset, Int32 count)
   at System.Xml.XmlBaseWriter.WriteBase64(Byte[] buffer, Int32 offset, Int32 count)
   at System.Xml.XmlDictionaryWriter.WriteValue(IStreamProvider value)
   at System.ServiceModel.Dispatcher.StreamFormatter.Serialize(XmlDictionaryWriter writer, Object[] parameters, Object returnValue)
   at System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
   at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
   at System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter writer)
   at System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
   at System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)
   at System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writer)
   at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Stream stream)
   at System.ServiceModel.Channels.HttpOutput.WriteStreamedMessage(TimeSpan timeout)
   at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, 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(MessageData& msgData, Int32 type)
   at test.CNTest.ITest.UploadDocument(UploadFileData request)
   at test.CNTest.TestClient.test.CNTest.ITest.UploadDocument(UploadFileData request) in C:\test\test\Service References\CNTest\Reference.cs:line 212
   at test.CNTest.TestClient.UploadDocument(String Desc, Int64[] evesId, Int64& Id, String Name, Int64 TokenId, String TokenKey, Int64 UserId, Stream FileByteStream, Boolean& IsSuccess) in C:\test\test\Service References\CNTest\Reference.cs:line 225
   at test.Form1.UploadFile() in C:\test\test\Form1.cs:line 390


请任何人对此都有解决方案.我想念什么吗?
我已经尝试过几乎所有的操作,例如更改服务器和客户端配置文件中的发送和接收超时值以及缓冲区大小,但是问题是相同的.请帮帮我.

在此先谢谢您.


Please anybody has solution for this. Am I missing something?
I have tried almost everything like changing the send and receive timeout values and buffer sizes in server and client config files but the problem is same.Please help me.

Thanks in advance.

推荐答案

我不知道您到底是什么人,但是文档确实为您提供了其他选择,也许您可​​以尝试:
http://msdn.microsoft.com/zh-我们/library/system.servicemodel.transfermode%28v=vs.110%29.aspx [
I dont know exactly what you rissue is, but the documentation does give you some other options perhaps you coul dtry that:
http://msdn.microsoft.com/en-us/library/system.servicemodel.transfermode%28v=vs.110%29.aspx[^]


这篇关于在WCF中使用流传输模式时发生超时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆