Windows 8 Store Apps Learning (63) Communication: WebSocket

Source: Internet
Author: User
Tags count httpcontext socket

Introduced

Re-imagine the Windows 8 Store Apps Communication

Socket-do Text communication with WebSocket server

Socket-Do Stream (Binary) communication with WebSocket server

Example

WebSocket Service-side

Webserver/websocketserver.ashx.cs

* * * WebSocket Protocol Server * * need to enable WebSocket protocol in IIS: Control Panel-> programs and features-> enable or turn off Windows features-> open IIS WebSocket protocol
* * using System;
Using System.IO;
Using System.Net.WebSockets;
Using System.Text;
Using System.Threading;
    
Using System.Web; Namespace WebServer {public class Websocketserver:ihttphandler {//The maximum size of the buffer to receive data private int _
    
        MaxBufferSize = 64 * 1024; public void ProcessRequest (HttpContext context) {try {//HTTPCONTEXT.ACC Eptwebsocketrequest ()-Accepts a WebSocket request context.
                    Acceptwebsocketrequest (Async wscontext =>//Aspnetwebsocketcontext {try
                        {byte[] Receivebuffer = new Byte[_maxbuffersize];
    
                        arraysegment<byte> buffer = new arraysegment<byte> (receivebuffer); Aspnetwebsocketcontext.websocket-Gets the WEBSO of the current contextCket object WebSocket socket = Wscontext.websocket; The HTTP handshake completes the IF (socket). state = = Websocketstate.open) {var outputstring = "WebSocket connecte
                            D: "+ DateTime.Now.ToString (" Mm:ss ");
    
                            arraysegment<byte> OutputBuffer = new Arraysegment<byte> (Encoding.UTF8.GetBytes (outputstring)); Websocket.sendasync ()-Send data//Websocketmessagetype.text-The number of text sent According to//websocketmessagetype.binary-Sent is binary data await socket.
                        SendAsync (OutputBuffer, Websocketmessagetype.text, True, Cancellationtoken.none); }//HTTP handshake complete while (socket. state = = Websocketstate.open) {//Websocket.receiveasync ()- Receives the data, returns the Websocketreceiveresult object Websocketreceiveresult Receiveresult = await socket.
    
                            Receiveasync (buffer, cancellationtoken.none); Websocketreceiveresult.messagetype-type of data received (Websocketmessagetype enumeration)//Websocketmes
                            Sagetype.text-Received text data//websocketmessagetype.binary-received binary data Websocketmessagetype.close-received a WebSocket shutdown message from the client if (receiveresult.message Type = = Websocketmessagetype.close) {//Websocket.closeasync ( )-Closes the WebSocket await socket.
                                    Closeasync (ReceiveResult.CloseStatus.GetValueOrDefault (),
    
                     Receiveresult.closestatusdescription, Cancellationtoken.none);           Return
    
                            int offset = Receiveresult.count; 
                            Websocketreceiveresult.endofmessage-whether the message is fully received while (Receiveresult.endofmessage = = False) {//Websocket.receiveasync ()-Receive data, return Websocketreceiveresul T object Receiveresult = await socket.
                                Receiveasync (New arraysegment<byte> (Receivebuffer, offset, _maxbuffersize-offset), Cancellationtoken.none);
                            Offset + + Receiveresult.count; //Receive Text data if (Receiveresult.messagetype = = Websocketmessage Type.text) {String receivedtext = Encoding.UTF8.GetString (rec
                                Eivebuffer, 0, offset); String sendtext = "Server toClient: \ "" + Receivedtext + "" "; Send text data to client arraysegment<byte> OutputBuffer = new Arraysegment<byte> (Encodin G.utf8.
                                GetBytes (SendText)); Await socket.
                            SendAsync (OutputBuffer, Websocketmessagetype.text, True, Cancellationtoken.none); //Receive binary data else if (Receiveresult.messagetype = = Websocketmessag Etype.binary) {String sendtext = "Server to client:binary Me
    
                                Ssage received, size: "+ receiveresult.count + bytes"; Send text data to client arraysegment<byte> OutputBuffer = new Arraysegment<byte> (Encodin G.utf8.
                                GetBytes (SendText)); Await socket.
       SendAsync (OutputBuffer, Websocketmessagetype.text, True, Cancellationtoken.none);                     catch (Exception ex)
            {
                            
                    }
                }); \ catch (Exception ex) {}} public bool IsR
            eusable {get {return false; }
        }
    }
}

1. Demo How to do Text communication through Messagewebsocket and WebSocket server

Communication/socket/messagewebsocketdemo.xaml

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/net/

Related Article

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.