【问题标题】:WCF Stream-Service push data to clientWCF Stream-Service 将数据推送到客户端
【发布时间】:2014-10-13 04:50:56
【问题描述】:

我目前正在处理使用 wcf 传输大字节数组的任务。

我尝试了以下代码,它可以工作:

在服务器端:

[OperationContract]
public System.IO.Stream GetData()
{
    FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
    return fs;
}

在客户端:

public void GetFile()
    {
        IByteService byteService = channelFactory.CreateChannel();
        Stream serverStream = byteService.GetData();

        byte[] buffer = new byte[2048];
        int bytesRead;

        FileStream fs = new FileStream(filePath, FileMode.CreateNew);

        while ((bytesRead = serverStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            fs.Write(buffer, 0, bytesRead);
        }
    }

但反之则不行:

在服务器端:

  [OperationContract]
   public void WriteToStream(Stream clientStream)
        {   
         FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
         fs.CopyTo(clientStream);
        }

在客户端:

public void SendStream()
{
    FileStream bytesReceivedFromTheServerAsFile = new FileStream(filePath,FileMode.OpenOrCreate);
    IByteService byteService = channelFactory.CreateChannel();

    byteService.WriteToStream(bytesReceivedFromTheServerAsFile);
}

fs.CopyTo(stream) 在服务器端抛出 NotSupportedException。

想知道为什么?

我想以其他方式进行下载,因为在服务器端我没有流。我将从第三方库接收字节。所以我想这样做:

在服务器端:

    [OperationContract]
   public void WriteToStream(Stream clientStream)
        {   
            byte[] buffer = new byte[2048]; // read in chunks of 2KB
            int bytesRead = 100;
            while ((ThirdPartyClass.GetNextBytes(buffer))
{
             clientStream.Write(buffer, 0, bytesRead);  
            }

        }

在客户端:

    public void SendStream()
    {
        FileStream bytesReceivedFromTheServerAsFile = new FileStream(filePath, FileMode.OpenOrCreate);
        IByteService byteService = channelFactory.CreateChannel();

        byteService.WriteToStream(bytesReceivedFromTheServerAsFile);
    }

因为我在服务器端没有流。我在想反过来将数据推送到客户端将是一个不错的方法。 但是,其他解决方案概念会很棒。

【问题讨论】:

  • 你最好使用base64传输流,如果传输大文件,必须在web配置中定义。

标签: c# wcf wcf-binding


【解决方案1】:

WCF 不支持这样推送流数据。请记住,客户端和服务器位于不同的内存空间中。服务器永远无法访问客户端拥有的对象。当您返回一个流时,WCF 为客户端构造了一种错觉,即客户端读取的流就是服务器返回的内容。 WCF 不能反过来做。

为自己编写一个从 3rd 方类读取的自定义流。从服务器返回该流。

【讨论】:

  • 既然可以通过base64或字节数组进行通信,为什么还要购买使用流的麻烦。
  • 据说他想流式传输数据。
  • 我想使用流,因为接收到的数据可以从 1Byte 到 X GByte。数据被分成包。我不知道我需要发送多少。我从第三图书馆收到一个又一个的包裹。所以我想把数据也一包一包地发送给客户端。
猜你喜欢
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多