无法通过WCF将流数据从客户端发送到服务器

时间:2019-07-10 07:59:21

标签: c# .net wcf

我正在尝试使用WCF中的流功能将一些数据从客户端发送到服务器。我可以读取从服务器返回的流,没有任何问题。但是,其他方法不起作用。

在用MessageContract装饰的类中尝试包装流,但没有成功。

客户端配置:

    <bindings>
      <netTcpBinding>
        <binding name="streamingBinding" transferMode="Streamed" 
    maxReceivedMessageSize="5000000000">
          <security mode="None" />
        </binding>
      </netTcpBinding>
    </bindings>

服务器配置:

    <bindings>
      <netTcpBinding>
        <binding name="streamingBinding" transferMode="Streamed" 
    maxReceivedMessageSize="5000000000">
          <security mode="None" />
        </binding>
      </netTcpBinding>
    </bindings>

...

    <service behaviorConfiguration="WcfSvc.WcfServiceBehavior" 
    name="Shared.StreamingService">
        <endpoint address="" binding="netTcpBinding" 
    bindingConfiguration="streamingBinding"
                  contract="Shared.IStreamingService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexTcpBinding" 
    bindingConfiguration=""
                  contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8733/StreamingTest/" />
          </baseAddresses>
        </host>
      </service>

主机应用:


    private static IStreamingService _service;
    private static ServiceHost _serviceHost;


    static void Main()
        {
            _service = new StreamingService();
            _serviceHost = new ServiceHost(_service);
            _serviceHost.Open();

            Console.WriteLine("Press enter to read data");
            Console.ReadLine();

            var stream = _service.GetData();
            var file = File.Create(@"PATH TO NON EXISTING FILE");
            stream.CopyTo(file);
            file.Close();

            Console.WriteLine("Press enter to close host");
            Console.ReadLine();

            _serviceHost.Close();
        }

客户端应用:

    private const string EndpointAddress = "net.tcp://localhost:8733/StreamingTest/";
        private const string TcpBindingConfigName = "streamingBinding";

        private static WcfChannelFactory<IStreamingService> _factory = new WcfChannelFactory<IStreamingService>();
        private static IStreamingService _service;
        private static ICommunicationObject _communicationObject;

        static void Main()
        {
            Console.WriteLine("Press enter to connect");
            Console.ReadLine();

            (_service, _communicationObject) = _factory.OpenAsync(EndpointAddress, TcpBindingConfigName).Result;

            var s = File.OpenRead(@"PATH TO EXISTING FILE");
            _service.SetData(s);

            Console.WriteLine("Press enter to disconnect");
            Console.ReadLine();

            _communicationObject.Close();
        }

服务:

    [ServiceContract(SessionMode = SessionMode.NotAllowed)]
    public interface IStreamingService
    {
        [OperationContract]
        void SetData(Stream data);

        [OperationContract]
        Stream GetData();
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class StreamingService : IStreamingService
    {
        private Stream _data;

        public void SetData(Stream data)
        {
            _data = data;
        }

        public Stream GetData()
        {
            return _data;
        }
    }

渠道工厂实施:

    public class WcfChannelFactory<TService>
    {
        private ChannelFactory<TService> _channelFactory;

        public async Task<(TService, ICommunicationObject)> OpenAsync(string endpointAddress, string tcpBindingConfigName)
        {
            var tcpBinding = new NetTcpBinding(tcpBindingConfigName);
            _channelFactory = new ChannelFactory<TService>(tcpBinding);
            await Task.Factory.FromAsync(_channelFactory.BeginOpen, _channelFactory.EndOpen, null);
            var wcf = _channelFactory.CreateChannel(new EndpointAddress(endpointAddress));
            return (wcf, wcf as ICommunicationObject);
        }

        public void Close()
        {
            _channelFactory?.Close();
            _channelFactory = null;
        }
    }

请在创建文件流的行上填写文件名。

运行主机和客户端后,在客户端窗口中按Enter,然后在主机窗口中引发异常:

System.ObjectDisposedException:无法访问关闭的Stream。 (在主机应用中的“ stream.CopyTo(file);”行上)

反向场景很好用(将文件从服务器发送到客户端)

2 个答案:

答案 0 :(得分:1)

我知道是什么引起了我的问题。问题在这里:

L.Rk / R

从GetData方法返回后,WCF自动关闭流。为了将流传播到服务类之外,我必须使用一个事件:

public Stream GetData()
{
    return _data;
}

,然后在事件处理程序中使用流。

答案 1 :(得分:0)

我建议您使用异步模型来构建/实现服务合同,因为文件流并不总是同步的。请参考以下代码段。

    [ServiceContract]
    interface IService
    {
        [OperationContract]
        Task UploadStream(Stream stream);
    }
    public class MyService : IService
    {
        public async Task UploadStream(Stream stream)
        {
            using (stream)
            {
                using (var file = File.Create(Path.Combine(Guid.NewGuid().ToString() + ".png")))
                {
                    await stream.CopyToAsync(file);
                }
            }
        }
}

调用。

  ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
        string file = Path.Combine(@"C:\", "1.png");
        FileStream fs = new FileStream(file,FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);

        //var s = File.OpenRead(file);

        //MemoryStream ms = new MemoryStream();
        //fs.CopyTo(ms);
        //ms.Position = 0;
        client.UploadStream(fs);
        Console.WriteLine("DOne");
        Console.ReadLine();

请随时告诉我是否有什么可以帮忙的。