SIGN UP MEMBER LOGIN:    
ARTICLE

Streaming in WCF

Posted by Dhananjay Kumar Articles | WCF with C# September 07, 2009
In this article, I am going to explain various aspects of streaming of messages in WCF.
Reader Level:

Objective

In this article, I am going to explain various aspects of streaming of messages in WCF. For example :

  1. I/O Streams
  2. Streaming and Binding
  3. Streaming and Transport channel
  4. Stream management

Why we need Streaming?

In WCF any receiving message is delivered only once entire message has been received. What I mean here is that first message is buffered at the receiving side and once it is fully received it gets delivered to the receiving end. Main problem with this approach is that receiver end is unresponsive while message is getting buffered. So default way of message handling in WCF is ok for small size messages but for the large size messages this approach is not good. So to overcome this problem Streaming in WCF come into action.

I/O Streams

WCF uses .Net Stream class for the purpose of streaming. There are no any changes while defining contract. It simply looks like normal contracts. Below contract is returning stream and taking stream input.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;

namespace OneWayService
{

    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        Stream ReturnStreamfromSeervice();

        [OperationContract]
        void ProcessStreamFromClient(Stream stream);

    }
}

  1. Parameter could be defined either as abstract base class Stream or Subclass MemoryStream
  2. Subclasses FileStream etc are not allowed as the type of parameters.

Steaming and Binding

  1. TCP, IPC and HTTP bindings support streaming.
  2. For all the Binding streaming is disabled by default.
  3. Streaming of the message should be enabled in the binding to override the buffering and enable the streaming.
  4. TransferMode property should be set according to the desired streaming mode in the bindings.
  5. Type of TransferMode property is enum TransferMode

    TransferMode enum type

    using System;
    namespace System.ServiceModel
    {

        public enum TransferMode
        {

            Buffered = 0,
            Streamed = 1,
            StreamedRequest = 2,
            StreamedResponse = 3,
        }
    }

     
  6. This property is defined in all the binding classes.

    TransferMode property in BasicHttpBinding class.

    using System;
    using System.ServiceModel.Channels;
    using System.Text;
    using System.Xml;

    namespace System.ServiceModel
    {
        public class BasicHttpBinding : Binding, IBindingRuntimePreferences
        {

            public TransferMode TransferMode { get; set; }
        }
    }

     

  7. TransferMode.Streamed supports all type of streaming modes. This supports all stream operations like receiving, returning.

  8. If you want to have buffer request and stream response TransferMode.StreamedResponse.

Configuring Streaming in Config file

<system.serviceModel>
                        <
services>
                                    <
service name="OneWayService.Service1" behaviorConfiguration="OneWayService.Service1Behavior" >
                                                <!-- Service Endpoints -->
                                                <
endpoint address="" binding="basicHttpBinding" bindingConfiguration="StreamedHttp" contract="OneWayService.IService1" >
                                                           
                                                            <
identity>
                                                                        <
dns value="localhost"/>
                                                            </identity>
                                                </
endpoint>
                                                <
endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
                                    </service>
                        </
services>
    <
bindings>
      <
basicHttpBinding>
        <
binding name ="StreamedHttp" transferMode ="Streamed" />
      </basicHttpBinding>
    </bindings>
                        <
behaviors>
                                    <
serviceBehaviors>
                                                <
behavior name="OneWayService.Service1Behavior">
                                                                                                                        <serviceMetadata httpGetEnabled="true"/>
                                                                                                                        <serviceDebug includeExceptionDetailInFaults="false"/>
                                                </behavior>
                                    </
serviceBehaviors>
                        </
behaviors>
            </system.serviceModel>

Increasing Message size

The default message size is 64K. But the message size in case of streaming may be very large. So default message size could be increased.
MaxReceivedMessageSize property of BasicHttpBinding class is used to increase the message size. Typical way of increasing message size is in config file.

<basicHttpBinding>
        <
binding name ="StreamedHttp" transferMode ="Streamed"  maxReceivedMessageSize ="100000"/>
      </basicHttpBinding>

Conclusion

I have explained all the facets related to Streaming in WCF. Thanks for reading.
Happy Coding
 

Login to add your contents and source code to this article
share this article :
post comment
 

Hello. I am developing REST Services in VB.NET Framework 4, to respond to mobile devices and need to send files types: PDF, XLS, PNG, JPG, GIF, and HTML. The file to send to the client, I can read it from the disk, becouse it is generated in a preceding function. In the case of an error, I need to send an error message in HTML format. Based on the attached example, somebody could help me with the code for each case? Thank you very much, I'm new to REST Services and HTML. Luigggye Imports System Imports System.Collections.Generic Imports System.Linq Imports System.ServiceModel Imports System.ServiceModel.Activation Imports System.ServiceModel.Web Imports System.Text Namespace MobileRestServices Public Class MobileFiles Public Property file As Object ' ------->> what kind of object is here for every file type ? End Class <ServiceContract()> <AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> <ServiceBehavior(InstanceContextMode:=InstanceContextMode.PerCall)> Public Class MobileRestServices <WebGet(UriTemplate:="ManageMobileQueries/{FileType}", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Bare)> Public Function ManageMobileFiles(ByVal FileType As String) As MobileFiles Dim Result As New MobileFiles Dim Status As Boolean = Call_Function_To_Generate_The_File(FileType) If Status = True Then Result.file = "HERE I WANT TO SET THE FILE FROM C:\FILES\....." Else Result.file = "HERE I WANT TO SET THE HTML WITH A MESSAGE ERROR" End If Return Result ' HERE I WANT TO RETURN THE FILE TO THE CLIENT (JSON RESULT ??) End Function End Class End Namespace

Posted by Luis Oliveira Dec 22, 2011

hi,
Iam exploring wcf.I have created a chat application using wcf in c#.net.It works properly but i want to add a feature where private chat between 2 clients must be allowed.When i send message all clients can view it.but what if i want to give a direct message to a particular client.Iam using netpeertcp.
According to the concept i think, i will have to create a new chat mesh between 2 clients required to pass message.I need to use pnrp tp resolve the addresses of clients so that i can identify the peer to chat with.
But i really dont knw how can i achieve this through code.iam new to wcf but know the concept as i went through number of msdn articles.how should i start the code?where should i write it?i just want a start n support so i can explore it further.
I really would be pleased n thankful if someone would help me in any way they can.waiting for reply.
THANKS.

Posted by Mumtaz Surani Sep 18, 2009
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor