[Silverlight Study Notes] Create duplex communication between Silverlight 3 and WCF

Source: Internet
Author: User
Tags: Silverlight, WCF, duplex communication

This article briefly describes a simple and efficient duplex application using WCF pulling duplex in silverlight3, a simple chat room (incomplete, just a demo );

1. the WCF Service will use the pollingduplex that comes with the Silverlight 3 SDK.

To add a reference to the system. servicemodel. pollingduplex assembly,

Note that the Silverlight 3 SDK contains two system. servicemodel. pollingduplex. DLL files,

One is referenced by the client, that is, in the Silverlight assembly,

Path: C: \ Program Files \ microsoft sdks \ Silverlight \ V3.0 \ libraries \Client\ System. servicemodel. pollingduplex. dll

The path of the DLL referenced by the WCF Service is c: \ Program Files \ microsoft sdks \ Silverlight \ V3.0 \ libraries \Server\ System. servicemodel. pollingduplex. dll

2. Define the callback service contract

The callback contract is an interface used by the WCF Service to push data to the Silverlight client:

[ServiceContract]   public interface IServiceCallback   {       [OperationContract(IsOneWay = true)]       void GetData(string data);   }

3. Define a service contract

MarkedServicecontractAndCallbackcontractSet to a valid type:

[ServiceContract(Namespace="",CallbackContract=typeof(IServiceCallback))]   public interface IService   {       [OperationContract(IsOneWay = true)]       void SentData(string data);       [OperationContract(IsOneWay = true)]       void InitData();   }

4. Call the callback contract method to push data to the client.

To send data to the client, we must first obtain a valid callback channel and one of the calling methods.

In this example, we callOperationcontext. Current. getcallbackchannel<Iduplexservicecallback> Get callback channel)

And call its getdata () method to push data to all online clients:

 

Public class service: iservice {static list <iservicecallback> cilents = new list <iservicecallback> (); Public void sentdata (string data) {iservicecallback isccurrent = operationcontext. current. getcallbackchannel <iservicecallback> (); int num = cilents. indexof (isccurrent); foreach (iservicecallback ISC in cilents) {try {ISC. getdata (Num + 1) + "said:" + data);} catch {}}}

}

5. Create a service host factory.

Manually create the service host factory to provide the service endpoint Configuration:

Public class authorization: servicehostfactorybase {public override servicehostbase createservicehost (string constructorstring, Uri [] baseaddresses) {// throw new topology (); return new topology (baseaddresses);} class authorization: servicehost {public pollingduplexsimplexservicehost (Params URI [] addresses) {base. initializedescription (typeof (service), new urischemekeyedcollection (addresses); base. description. behaviors. add (New servicemetadatabehavior ();} protected override void initializeruntime () {// Add an endpoint to the service this. addserviceendpoint (typeof (iservice), new custombinding (New pollingduplexbindingelement (), new binarymessageencodingbindingelement (), new httptransportbindingelement (), ""); // Add metadata endpoint this. addserviceendpoint (typeof (imetadataexchange), metadataexchangebindings. createmexhttpbinding (), "mex"); base. initializeruntime ();}}
Then add the factory to the service:
<%@ ServiceHost Language="C#" Debug="true" Service="SevendaysDuplex.Web.Service" CodeBehind="Service.svc.cs"
 Factory="SevendaysDuplex.Web.PollingDuplexServiceHostFactory" %>

Before running this service, delete all WCF-related configurations in the web. config file.

6. Add a service reference in the Silverlight project.

Note that servicereferences. clientconfig does not generate content when you add a reference to a duplex service. Therefore, you must manually pass the endpoint and address configuration to the service client:

ServiceClient _sc;        public ServiceClient SC        {            get            {                if (_sc == null)                {                    EndpointAddress address = new EndpointAddress(GetAbsoluteUri("Service.svc"));                    CustomBinding binding = new CustomBinding(                        new PollingDuplexBindingElement(),                        new BinaryMessageEncodingBindingElement(),                        new HttpTransportBindingElement());                    _sc = new ServiceClient(binding, address);                    _sc.GetDataReceived += new EventHandler<GetDataReceivedEventArgs>(_sc_GetDataReceived);                }                return _sc;            }        }

7. Use Services

Using duplex services is very simple. It is no different from consuming other WCF services. We only need to process the getdatareceived event (because our callback contract discloses the getdata method) and let the WCF process Client/Server Communication.

void _sc_GetDataReceived(object sender, GetDataReceivedEventArgs e)        {            //throw new NotImplementedException();            LBMessage.Items.Add(e.data);        }
 

Download sample source code 

 

Tags: Silverlight, WCF, duplex communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.