简体   繁体   中英

Can't send streamed data from client to server via WCF

I'm trying to send some data from client to server using streaming functionality in WCF. I can read stream returned from server with no issues. Other way around doesn't work however.

Tried wrapping stream in class decorated with MessageContract with no success.

Client config:

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

Server config:

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

Host app:


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

Client app:

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

Service:

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

Channel factory implementation:

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

Please fill file names at lines where file streams are created.

After running host and client, pressing enter in client window and then in host window exception is thrown:

System.ObjectDisposedException: Cannot access a closed Stream. (on line 'stream.CopyTo(file);' in host app)

Reverse scenario works just fine (sending file from server to client)

I know what caused my problem. The problem is here:

public Stream GetData()
{
    return _data;
}

After returning from GetData method WCF automatically closes the stream. To propagate the stream outside of the service class I had to use an event:

public event Action<StreamMessage> DataSet; 

public void SetData(StreamMessage data)
{
    _data = data;
    DataSet?.Invoke(data);
}

and then consume the stream in the event handler.

I suggest you use the Asynchronous model to build/implement the Service contract, since the file stream is not always synchronized. Please refer to the below code segments.

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

Invocation.

  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();

Feel free to let me know if there is anything I can help with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM