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

本文关键字:客户端 错误 | 更新日期: 2023-09-27 17:56:02

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

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

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

[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 ---

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

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

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

[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);
}

注意:如果您注意到我用DataContract更改了可序列化的注释,因为它比可序列化有几个优点。如果要传递大型数据,也可以考虑这几个设置。

如果你真的想在管道中传递流,有几个链接在网中出其他。

前任。

  • 通过 WCF 流式传输文件
  • WCF-Streaming-Upload-Download-Files-over-HTTP