Silverlight and WCF Service duplex communication Article 1: pollingduplexhttpbinding

Source: Internet
Author: User

Using pollingduplexhttpbinding to implement duplex communication (pushing messages from the WCF server to the client) is a relatively "old-style" approach. in versions earlier than silverlight4, Silverlight does not support net. TCP communication, so it can only be achieved by packaging HTTP Communication.

However, after all, no one can penetrate the firewall through HTTP, so pollingduplexhttpbinding may be used to implement duplex.

1. Create a demo project

Create a Silverlight project in vs (I use silverlight5 ,. net 4.5), named slhttppollingduplexsample. Next, create a new Web application to host this SL project. The web application is automatically named slhttppollingduplexsample. web.

2. Create a service

2.1In slhttppollingduplexsample. right-click a web project and choose add new item> WCF Service. The project name is service1.svc because it is a demo project. two new files are added to the project: iservice. CS and service1.svc.

Change iservice1.cs to the following content:

namespace SLHttpPollingDuplexSample.Web{    [ServiceContract(CallbackContract = typeof(IClientCallback))]    public interface IService1    {        [OperationContract]        void Register();    }    public interface IClientCallback    {        [OperationContract(IsOneWay = true)]        void PushMessage(string message);    }}

Let's take a look at this interface file:

Iservice1 is a service interface, which includes a register method. When the client calls this method, it means that it wants to subscribe to the server for information. When the server pushes the information, the information will be pushed to this client. (Of course, an unsubscribe function is required in reality, but the basic function is only demonstrated here)

The following interface iclientcallbak is a callback interface. When the server needs to push messages to the client, this interface is used to push messages.

 

2.2Change service1.svc. CS to the following content:

    public class Service1 : IService1    {        public Service1()        {            new System.Threading.Thread(PumpMessage).Start();        }        private static Dictionary<IClientCallback, byte> _clients = new Dictionary<IClientCallback, byte>();        public void Register()        {            var c = OperationContext.Current.GetCallbackChannel<IClientCallback>();            if (!_clients.ContainsKey(c))            {                lock (_clients)                {                    _clients.Add(c, 0);                }            }        }        private void PumpMessage()        {            var deadClients = new List<IClientCallback>();            while (true)            {                System.Threading.Thread.Sleep(10000);                if (_clients.Count < 1)                    continue;                foreach (var c in _clients.Keys)                {                    try                    {                        c.PushMessage(DateTime.Now.ToString("HH:mm:ss"));                    }                    catch                    {                        deadClients.Add(c);                    }                }                if (deadClients.Count > 0)                {                    lock (_clients)                    {                        deadClients.ForEach(b => _clients.Remove(b));                    }                    deadClients.Clear();                }            }        }    }

About this class:

Pumpmessage is a simple automatic push message pump that sends a message (current time) to the client every 10 seconds ). if the push fails, the client is taken offline and deleted from the client list.

_ Clients is a static client list. Although it is a dictionary type, its value is useless. Here, it only uses the dictionary's quick key retrieval function, therefore, the value part is always 0.

The register implementation is also very simple and clear. It directly adds the current channel to _ clients.

 

2.3 add reference and web. config Configuration

Pollingduplex is not part of the default. net, so you must add this DLL file to the project by adding references.

Right-click the project and choose add reference> browse,

Find c: \ Program Files \ microsoft sdks \ Silverlight \ V5.0 \ libraries \ Server \ system. servicemodel. pollingduplex. dll.

Note that there is also a DLL file with the same name in the client file. You must select the server folder here.

After the reference is complete, configure as follows in the <system. servicemodel> section of Web. config:

  <system.serviceModel>    <bindings>      <pollingDuplexHttpBinding>        <binding name="pollingDuplexHttpBinding1" duplexMode="MultipleMessagesPerPoll" maxOutputDelay="00:00:00.2"/>      </pollingDuplexHttpBinding>    </bindings>    <services>      <service name="SLHttpPollingDuplexSample.Web.Service1">        

 

2.4 release and cross-origin permission settings

Publish slhttppollingduplexsample. Web to any directory, and add-> application in IIS to add this directory to IIS.

Then, you need to place a Cross Domain Policy (clientaccesspolicy. XML) file under the root directory of the website to allow SL access.

<?xml version="1.0" encoding ="utf-8"?><access-policy>  <cross-domain-access>    <policy>      <allow-from>        <domain uri="*"/>      </allow-from>      <grant-to>        <resource path="/" include-subpaths="true"/>        <socket-resource port="4502-4506" protocol="tcp" />      </grant-to>    </policy>  </cross-domain-access></access-policy>

 

3. Configure the SL end

Add service reference (address: http: // localhost/slhttppollingduplexsample) to the SL project. web/service1.svc), but because vs does not have built-in support for pollingduplex, the generated servicereferences. clientconfig is empty. this file is not used here. You can use the code to create an endpoint.

System must be referenced in the SL project. servicemodel. pollingduplex. DLL Client Version, but in my vs2012, after adding a service reference, it will be automatically referenced. It seems that vs2010 does not have this function. if the system is not displayed in the reference of the SL project. servicemodel. pollingduplex, you need to go to the above reference Server DLL location, find the library \ Client folder, reference the following system. servicemodel. pollingduplex. DLL.

Put a text box txt1 and a button btn1 in mainpage of SL. In the Click Event of the button btn1:

        private void btn1_Click_1(object sender, RoutedEventArgs e)        {            var address = new EndpointAddress("http://localhost/SLHttpPollingDuplexSample.Web/Service1.svc");            var binding = new PollingDuplexHttpBinding(PollingDuplexMode.MultipleMessagesPerPoll);            var proxy = new ServiceReference1.Service1Client(binding, address);            proxy.PushMessageReceived += proxy_PushMessageReceived;            proxy.RegisterAsync();        }        void proxy_PushMessageReceived(object sender, ServiceReference1.PushMessageReceivedEventArgs e)        {            txt1.Text = e.message;        }

Set the automatically generated slhttppollingduplexsample.webproject slhttppollingduplexsampletestpage.html as the starting item. Run F5. After you see the SL interface, click a button btn1. Wait a moment and you will see a time in the text box, that is the data pushed by the server.

 

Conclusion: This method is just an alternative. Generally, if. TCP is available. net. is preferred. TCP for communication. about using net. for TCP to implement duplex, see the next article Silverlight and WCF Service duplex communication Article 2: net. TCP binding

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.