将“Stream”传递给客户端会引发错误

时间:2016-07-09 01:00:34

标签: c# http serialization soap stream

下面的struct是可序列化的,当服务器(运行WCF Web服务)返回此对象时,客户端可以正确接收数据。

[Serializable]
public struct TestInfo
{
    public string TestStr;
    public int TestInt;
}

场景:服务器正在尝试打开端点并将其发送到客户端,以便客户端将文件写入其中。我尝试在结构中添加'Stream',如下所示,但它会抛出错误。

[Serializable]
public struct TestInfo
{
    public string TestStr;
    public int TestInt;
    public Stream TestStream;
}

错误:

An error occurred while receiving the HTTP response. 
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). 
System.Net.WebException: The underlying connection was closed: 
An unexpected error occurred on a receive. ---> 
System.IO.IOException: Unable to read data from the transport connection: 
An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
    at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

--- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)

at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)

at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)

at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)

at System.Net.TlsStream.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)

--- End of inner exception stack trace ---

at System.Net.HttpWebRequest.GetResponse()

at     System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

   --- End of inner exception stack trace ---

知道我在这里遗漏了什么吗? 'Stream'是可序列化的,我认为发送Stream会很好。如果'Stream'不是最佳方式,那么我可以尝试其他任何方式吗?

1 个答案:

答案 0 :(得分:0)

传输文件的另一种方法是将文件内容转换为字节,并在数据协定中添加文件名数据成员。

[DataContract]
public struct TestInfo
{    
    [DataMember]
    public string FileName;   
    [DataMember]
    public byte [] FileStream;
}

在系统中写一个文件

using(var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
    stream.CopyTo(fileStream);
}

注意:如果您注意到我使用enter image description here更改了Serializable注释,因为它比Serializable有一些优势。如果您想要DataContract,也可以考虑这几个设置。

如果你真的想在管道中传递流,那么网中会有一些链接出来。

实施例。