WCF websocketsservice (HTML5 websocket)

Source: Internet
Author: User

In Web applications, the HTTP protocol determines that the connection between the client and the server is "short connection", that is, the client request, the server response, and the connection is disconnected. To realize real-time communication between the client and the server, you can only achieve this through client polling. "Server push data" is not literally a "direct push", but is actually "self-Fetch" by the client ". In the HTML5 standard, the newWebsocketThe protocol allows unlimited connections between the client and the server. websocket is faster, cheaper, and simpler. Websocket can be used to replace the previous Ajax client round-robin to push data from the server to the client. (Ie9 does not support websocket. The following is a test conducted by the Chrome browser: chrome 14.0.835.186 m)

Update:

Chrome 14 uses: sec-websocket-version: 7 (successful)
Chrome 17 uses: sec-websocket-Version: 13 (failed)
It indicates that the current websocket version supported by websocketsservice is less than 13.

. Net also supports websocket, but it does not provide official download. However, you can also get Microsoft. servicemodel. websockets. dll from the demo downloaded by html5lib.

1. Create a websocket service:

Here the websocketsservice is inherited and the service instance uses persession, so that each client connection corresponds to an instance. (Exceptions are thrown when websocketsservice uses singleton)
The following code is mainly implemented:
(1) When the client connects, save the service instance to list <websocketsservice>.
(2) when the client is disconnected, remove the service instance list <websocketsservice>
(3) return the active service instance set

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession,                     ConcurrencyMode = ConcurrencyMode.Multiple)]    public class NotificationService : WebSocketsService    {        public static event Action<WebSocketsService, string> MessageReceieved;        private static List<NotificationService> _serviceContainer = new List<NotificationService>();        public static List<NotificationService> ActivityServices        {            get             {                return _serviceContainer;            }        }        public override void OnMessage(string value)        {            base.OnMessage(value);            if (MessageReceieved != null)                MessageReceieved(this, value);            Console.WriteLine(value);        }        public override void OnOpen()        {            base.OnOpen();            base.SendMessage("Welcome");            Console.WriteLine("Client Opened");            _serviceContainer.Add(this);        }        protected override void OnError(object sender, EventArgs e)        {            base.OnError(sender, e);            Console.WriteLine("Client Error");        }        protected override void OnClose(object sender, EventArgs e)        {            base.OnClose(sender, e);            Console.WriteLine("Client Closed");            _serviceContainer.Remove(this);        }    } 

Create another host:

To demonstrate the effect of server push, a task is added and a message is sent to the client every two seconds.
Different from wshttpbinding and nettcpbinding's WCF servicehost, websocketshost is used, and the address schema is "ws" or "WSS" (based on SSL)

 class Program {     static void Main(string[] args)     {         var baseAddress = new Uri("ws://localhost:20001/NotificationService");         using (var host = new WebSocketsHost<NotificationService>(baseAddress))         {             host.AddWebSocketsEndpoint();             host.Open();             Console.WriteLine(baseAddress.ToString() + " Opened ...");             var task = new Task(() => {                 while (true)                 {                     System.Threading.Thread.Sleep(2000);                     try                     {                         Console.WriteLine("Service Instance Count:" + NotificationService.ActivityServices.Count);                         NotificationService.ActivityServices.                             ForEach(s => s.SendMessage("Service Message: " + DateTime.Now.ToLongTimeString()));                     }                     catch(Exception ex)                     {                         Console.WriteLine("Error: " + ex.Message);                     }                 }             });             task.Start();             Console.Read();         }     } }

2. html client:
Websocket objects are directly built in HTML5, which is very simple to operate. For more information, see: http://dev.w3.org/html5/websockets/

3. Running effect:
Server:

Client:

4. Notes:
(1) websocket will automatically disconnect if there is no message communication within 5 minutes
(2) websocket implements handshake over HTTP for the first time, and then communicates directly through TCP
(3) CAN communication between the two parties penetrate through the NAT network environment? Awaiting study...

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.