ARTICLE

Web Socket in Windows Store Apps

Posted by Deepak Arora Articles | Windows Store Apps October 20, 2012
In this article I described how to create a Windows Store App to to use a Message Web Socket to send UTF-8 strings using JavaScript.
Reader Level:

Introduction

Today we are going to learn how to create Windows Store Apps to use a Message Web Socket to send UTF-8 strings using JavaScript. You can enter the text in the text box to send a message to the server. By default "server Address" is disabled and URI validation is not required. When enabling the text box validating the URI is required since it was received from an untrusted source.

The URI is validated by calling validate and create Uri() that will return "null" for strings that are not valid Web Socket URIs. Note that, when enabling the text box, users may provide URIs to machines on the intranet or internet. In these cases the app requires the "Home or Work Networking" or "Internet (Client)" capability respectively.

I assume you can create a simple Windows Store App using JavaScript; for more help visit Simple Windows Store Apps using JavaScript.

To start the creation of the apps, add three JavaScript pages by right-clicking on the js folder in the Solution Explorer and select Add > new item > JavaScript Page and then give an appropriate name. In the same way, add one HTML page to your project.

websocket=Windows-store-apps.jpg

Write the following code in default.html:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title>app</title>

    <link rel="stylesheet" href="//Microsoft.WinJS.1.0/css/ui-light.css" />

    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>

    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

    <link rel="stylesheet" href="/css/default.css" />

    <script src="/js/script.js"></script>

    <script src="/js/default.js"></script>

</head>

<body role="application" style="background-color: lightgreen">

    <center><div id="rootGrid">      

        <div id="content">

            <h1 id="featureLabel"></h1>

            <div id="contentHost"></div>

        </div>       

    </div></center>

</body>

</html>

Write the following code in default.js:
 

(function () {

    "use strict";

    var appTitle = "";

    var pages = [

 

        { url: "page.html" }

    ];

    function activated(eventObject) {

        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            eventObject.setPromise(WinJS.UI.processAll().then(function () {

                var url = WinJS.Application.sessionState.lastUrl || pages[0].url;

                return WinJS.Navigation.navigate(url);

            }));

        }

    }

    WinJS.Navigation.addEventListener("navigated", function (eventObject) {

        var url = eventObject.detail.location;

        var host = document.getElementById("contentHost");

        host.winControl && host.winControl.unload && host.winControl.unload();

        WinJS.Utilities.empty(host);

        eventObject.detail.setPromise(WinJS.UI.Pages.render(url, host, eventObject.detail.state).then(function () {

            WinJS.Application.sessionState.lastUrl = url;

        }));

    });

    WinJS.Namespace.define("App", {

        appTitle: appTitle,

        pages: pages

    });

    WinJS.Application.addEventListener("activated", activated, false);

    WinJS.Application.start();

})(); 


Write the following code in Page.html:
 

<!DOCTYPE html>

<html xmlns>

<head>

    <title></title>

    <link rel="stylesheet" href="/css/page1.css" />

    <script src="/js/script2.js"></script>

    <script src="/js/script.js"></script>

</head>

<body>

    <p>

        <label for="serverAddress">Server address: </label>

        <input type="text" id="serverAddress" value="ws://localhost/20_10_2012/Echo20_10_2012.ashx" size="60" /></p>

    <p>

        <label for="inputField">Enter text </label>

        <input type="text" id="inputField" value="Hello World" /></p>

    <p>

        <button id="startButton">Start</button>

    </p>

    <div data-win-control="App.pageOutput">

        <div id="outputField" />

    </div>

</body>

</html>


Write the following code in script.js:
 

(function () {

    "use strict";

    var messageWebSocket;

    var messageWriter;

    var page = WinJS.UI.Pages.define("page.html", {

        ready: function (element, options) {

            document.getElementById("startButton").addEventListener("click", startSend, false);

        },

        unload: function (eventArgument) {

            closeSocket();

        }

    });

    function startSend() {

        if (document.getElementById("inputField").value === "") {

            WinJS.log && WinJS.log("Please specify text to send", "app", "error");

            return;

        }

        if (!messageWebSocket) {

            var webSocket = new Windows.Networking.Sockets.MessageWebSocket();

            webSocket.control.messageType = Windows.Networking.Sockets.SocketMessageType.utf8;

            webSocket.onmessagereceived = onMessageReceived;

            webSocket.onclosed = onClosed;

            var uri = validateAndCreateUri(document.getElementById("serverAddress").value);

            if (!uri) {

                return;

            }

            WinJS.log && WinJS.log("Connecting to: " + uri.absoluteUri, "app", "status");

            webSocket.connectAsync(uri).done(function () {

                WinJS.log && WinJS.log("Connected", "app", "status");

                messageWebSocket = webSocket;

                messageWriter = new Windows.Storage.Streams.DataWriter(webSocket.outputStream);

                sendMessage();

            }, function (error) {

                var errorStatus = Windows.Networking.Sockets.WebSocketError.getStatus(error.number);

                if (errorStatus === Windows.Web.WebErrorStatus.cannotConnect ||

                    errorStatus === Windows.Web.WebErrorStatus.notFound ||

                    errorStatus === Windows.Web.WebErrorStatus.requestTimeout) {

                    WinJS.log && WinJS.log("Cannot connect to the server. Please make sure " +

                        "to run the server setup script before running the app.", "app", "error");

                }

                else {

                    WinJS.log && WinJS.log("Failed to connect: " + getError(error), "app", "error");

                }

            });

        }

        else {

            WinJS.log && WinJS.log("Already Connected", "app", "status");

            sendMessage();

        }

    }

    function onMessageReceived(args) {

        var dataReader = args.getDataReader();

        log("Message Received; Type: " + getMessageTypeName(args.messageType)

            + ", Bytes: " + dataReader.unconsumedBufferLength + ", Text: ");

        log(dataReader.readString(dataReader.unconsumedBufferLength));

    }

    function getMessageTypeName(messageType) {

        switch (messageType) {

            case Windows.Networking.Sockets.SocketMessageType.utf8:

                return "UTF-8";

            case Windows.Networking.Sockets.SocketMessageType.binary:

                return "Binary";

            default:

                return "Unknown";

        }

    }

    function sendMessage() {

        log("Sending message");

        messageWriter.writeString(document.getElementById("inputField").value);

        messageWriter.storeAsync().done("", sendError);

    }

    function sendError(error) {

        log("Send error: " + getError(error));

    }

    function onClosed(args) {

        log("Closed; Code: " + args.code + " Reason: " + args.reason);

        if (!messageWebSocket) {

            return;

        }

 

        closeSocketCore();

    }

    function closeSocket() {

        if (!messageWebSocket) {

            WinJS.log && WinJS.log("Not connected", "app", "status");

            return;

        }

        WinJS.log && WinJS.log("Closing", "app", "status");

        closeSocketCore(1000, "Closed due to user request.");

    }

    function closeSocketCore(closeCode, closeStatus) {

        if (closeCode && closeStatus) {

            messageWebSocket.close(closeCode, closeStatus);

        } else {

            messageWebSocket.close();

        }

        messageWebSocket = null;

 

        if (messageWriter) {

            messageWriter.close();

            messageWriter = null;

        }

    }

    function log(text) {

        document.getElementById("outputField").innerHTML += text + "<br>";

    }

})(); 


Write the following code in script1.js:
 

(function () {

    var pageOutput = WinJS.Class.define(

        function (element, options) {

            element.winControl = this;

            this.element = element;

            new WinJS.Utilities.QueryCollection(element)

                        .setAttribute("role", "region")

                        .setAttribute("aria-labelledby", "outputLabel")

                        .setAttribute("aria-live", "assertive");

            element.id = "output";

 

            this._addOutputLabel(element);

            this._addStatusOutput(element);

        }, {

            _addOutputLabel: function (element) {

                var label = document.createElement("h2");

                label.id = "outputLabel";

                label.textContent = "Output";

                element.parentNode.insertBefore(label, element);

            },

            _addStatusOutput: function (element) {

                var statusDiv = document.createElement("div");

                statusDiv.id = "statusMessage";

                element.insertBefore(statusDiv, element.childNodes[0]);

            }

        }

    );

    var currentpageUrl = null;

    WinJS.Navigation.addEventListener("navigating", function (evt) {

        currentpageUrl = evt.detail.location;

    });

    WinJS.log = function (message, tag, type) {

        var statusDiv = document.getElementById("statusMessage");

    };

    function activated(e) {

        WinJS.Utilities.query("#featureLabel")[0].textContent = App.appTitle;

    }

    WinJS.Application.addEventListener("activated", activated, false);

    WinJS.Namespace.define("App", {

        pageOutput: pageOutput

    });

})();


Write the following code in script2.js:
 

function getError(e) {

    var webSocketError = Windows.Networking.Sockets.WebSocketError.getStatus(e.number);

    switch (webSocketError) {

        case Windows.Web.WebErrorStatus.unknown: return e;

        case Windows.Web.WebErrorStatus.certificateCommonNameIsIncorrect: return "CertificateCommonNameIsIncorrect";

        case Windows.Web.WebErrorStatus.certificateExpired: return "CertificateExpired";

        case Windows.Web.WebErrorStatus.certificateContainsErrors: return "CertificateContainsErrors";

        case Windows.Web.WebErrorStatus.certificateRevoked: return "CertificateRevoked";

        case Windows.Web.WebErrorStatus.certificateIsInvalid: return "CertificateIsInvalid";

        case Windows.Web.WebErrorStatus.serverUnreachable: return "ServerUnreachable";

        case Windows.Web.WebErrorStatus.timeout: return "Timeout";

        case Windows.Web.WebErrorStatus.errorHttpInvalidServerResponse: return "ErrorHttpInvalidServerResponse";

        case Windows.Web.WebErrorStatus.connectionAborted: return "ConnectionAborted";

        case Windows.Web.WebErrorStatus.connectionReset: return "ConnectionReset";

        case Windows.Web.WebErrorStatus.disconnected: return "Disconnected";

        case Windows.Web.WebErrorStatus.httpToHttpsOnRedirection: return "HttpToHttpsOnRedirection";

        case Windows.Web.WebErrorStatus.httpsToHttpOnRedirection: return "HttpsToHttpOnRedirection";

        case Windows.Web.WebErrorStatus.cannotConnect: return "CannotConnect";

        case Windows.Web.WebErrorStatus.hostNameNotResolved: return "HostNameNotResolved";

        case Windows.Web.WebErrorStatus.operationCanceled: return "OperationCanceled";

        case Windows.Web.WebErrorStatus.redirectFailed: return "RedirectFailed";

        case Windows.Web.WebErrorStatus.unexpectedStatusCode: return "UnexpectedStatusCode";

        case Windows.Web.WebErrorStatus.unexpectedRedirection: return "UnexpectedRedirection";

        case Windows.Web.WebErrorStatus.unexpectedClientError: return "UnexpectedClientError";

        case Windows.Web.WebErrorStatus.unexpectedServerError: return "UnexpectedServerError";

        case Windows.Web.WebErrorStatus.multipleChoices: return "MultipleChoices (300)";

        case Windows.Web.WebErrorStatus.movedPermanently: return "MovedPermanently (301)";

        case Windows.Web.WebErrorStatus.found: return "Found (302)";

        case Windows.Web.WebErrorStatus.seeOther: return "SeeOther (303)";

        case Windows.Web.WebErrorStatus.notModified: return "NotModified (304)";

        case Windows.Web.WebErrorStatus.useProxy: return "UseProxy (305)";

        case Windows.Web.WebErrorStatus.temporaryRedirect: return "TemporaryRedirect (307)";

        case Windows.Web.WebErrorStatus.badRequest: return "BadRequest (400)";

        case Windows.Web.WebErrorStatus.unauthorized: return "Unauthorized (401)";

        case Windows.Web.WebErrorStatus.paymentRequired: return "PaymentRequired (402)";

        case Windows.Web.WebErrorStatus.forbidden: return "Forbidden (403)";

        case Windows.Web.WebErrorStatus.notFound: return "NotFound (404)";

        case Windows.Web.WebErrorStatus.methodNotAllowed: return "MethodNotAllowed (405)";

        case Windows.Web.WebErrorStatus.notAcceptable: return "NotAcceptable (406)";

        case Windows.Web.WebErrorStatus.proxyAuthenticationRequired: return "ProxyAuthenticationRequired (407)";

        case Windows.Web.WebErrorStatus.requestTimeout: return "RequestTimeout (408)";

        case Windows.Web.WebErrorStatus.conflict: return "Conflict (409)";

        case Windows.Web.WebErrorStatus.gone: return "Gone (410)";

        case Windows.Web.WebErrorStatus.lengthRequired: return "LengthRequired (411)";

        case Windows.Web.WebErrorStatus.preconditionFailed: return "PreconditionFailed (412)";

        case Windows.Web.WebErrorStatus.requestEntityTooLarge: return "RequestEntityTooLarge (413)";

        case Windows.Web.WebErrorStatus.requestUriTooLong: return "RequestUriTooLong (414)";

        case Windows.Web.WebErrorStatus.unsupportedMediaType: return "UnsupportedMediaType (415)";

        case Windows.Web.WebErrorStatus.requestedRangeNotSatisfiable: return "RequestedRangeNotSatisfiable (416)";

        case Windows.Web.WebErrorStatus.expectationFailed: return "ExpectationFailed (417)";

        case Windows.Web.WebErrorStatus.internalServerError: return "InternalServerError (500)";

        case Windows.Web.WebErrorStatus.notImplemented: return "NotImplemented (501)";

        case Windows.Web.WebErrorStatus.badGateway: return "BadGateway (502)";

        case Windows.Web.WebErrorStatus.serviceUnavailable: return "ServiceUnavailable (503)";

        case Windows.Web.WebErrorStatus.gatewayTimeout: return "GatewayTimeout (504)";

        case Windows.Web.WebErrorStatus.httpVersionNotSupported: return "HttpVersionNotSupported (505)";

        default: return e;

    }

};

function validateAndCreateUri(uriString) {

    var webSocketUri;

    try {

        webSocketUri = new Windows.Foundation.Uri(uriString);

    } catch (error) {

        WinJS.log && WinJS.log("Error: Invalid URI", "app", "error");

        return null;

    }

    if (webSocketUri.fragment !== "") {

        WinJS.log && WinJS.log("Error: URI fragments not supported in WebSocket URIs.", "app", "error");

        return null;

    }

    var scheme = webSocketUri.schemeName;

    if ((scheme !== "ws") && (scheme !== "wss")) {

        WinJS.log && WinJS.log("Error: WebSockets only support ws:// and wss:// schemes.", "app", "error");

        return null;

    }

    return webSocketUri;

} 


Output:

websocket-windows-stores-apps.jpg

Summary

In this article I described how to create a Windows Store App to to use a Message Web Socket to send UTF-8 strings using JavaScript. I hope this article has helped you in understanding this topic. Please share it. If you know more about this, your feedback and constructive contributions are welcome.

COMMENT USING