Introduction
In this article I describe how to create Windows Store App for Datagram Socket Listener using JavaScript. A Datagram Socket is used to create the "server" side of a connection. It listens on a "service name" (often a port number) and each time a datagram is received on the port number it fires a MessageReceived event.
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 two JavaScript pages by right-clicking on the js folder in the Solution Explorer and select "Add" > "New item" > "JavaScript Page" and then provide an appropriate name. In the same way, add a HTML page to your project.
Write the following code in the default.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></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/default.js"></script>
</head>
<body role="application" style="background-color: lightgoldenrodyellow">
<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 the default.js:
(function () {
"use strict";
var appTitle = "DatagramSocket";
var pagess = [
{ url: "page.html", title: "Close Socket" }
];
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 the page.html:
<!DOCTYPE html>
<html>
<head>
<script src="/js/script1.js"></script>
<script src="/js/script.js"></script>
</head>
<body>
<div data-win-control="App.pageInput">
<p>
<label for="serviceNameAccept">Service Name:</label>
<input id="serviceNameAccept" type="text" />
</p>
<p>
<button id="buttonStartListener">Listen</button>
</p>
</div>
<div data-win-control="App.pageOutput">
<p id="statusBox"></p>
<p id="outputBox"></p>
</div>
</body>
</html>
Write the following code in the script.js:
(function () {
"use strict";
var page = WinJS.UI.Pages.define("page.html", {
ready: function (element, options) {
document.getElementById("buttonStartListener").addEventListener("click", startListener, false);
document.getElementById("serviceNameAccept").addEventListener("change", socketsapp.getValues, false);
socketsapp.setValues();
}
});
function startListener() {
var serviceName = document.getElementById("serviceNameAccept").value;
if (serviceName === "") {
socketsapp.displayStatus("Please provide a service name.");
return;
}
if (socketsapp.listener) {
socketsapp.displayStatus("Already have a listener; call close to close the listener.");
return;
}
socketsapp.closing = false;
socketsapp.bindingToService = true;
socketsapp.listener = new Windows.Networking.Sockets.DatagramSocket();
socketsapp.listener.addEventListener("messagereceived", onServerMessageReceived);
socketsapp.displayStatus("Server: listener creation started.");
socketsapp.listener.bindServiceNameAsync(serviceName).done(function () {
socketsapp.displayStatus("Server: listener creation completed.");
socketsapp.bindingToService = false;
}, onError);
}
function onServerMessageReceived(eventArgument) {
if (socketsapp.listenerOutputStream) {
echoMessage(socketsapp.listenerOutputStream, eventArgument);
return;
}
socketsapp.listener.getOutputStreamAsync(eventArgument.remoteAddress, eventArgument.remotePort).done(function (outputStream) {
if (!socketsapp.listenerOutputStream) {
socketsapp.listenerOutputStream = outputStream;
socketsapp.listenerPeerAddress = eventArgument.remoteAddress;
socketsapp.listenerPeerPort = eventArgument.remotePort;
}
echoMessage(socketsapp.listenerOutputStream, eventArgument);
});
}
function echoMessage(outputStream, eventArgument) {
if (socketsapp.listenerPeerAddress !== eventArgument.remoteAddress ||
socketsapp.listenerPeerPort !== eventArgument.remotePort) {
socketsapp.displayStatus("Got datagram from " + eventArguments.remoteAddress + ":" + eventArguments.remotePort +
", but already 'connected' to " + socketsapp.listenerPeerAddress + ":" + socketsapp.listenerPeerPort);
return;
}
outputStream.writeAsync(eventArgument.getDataReader().detachBuffer()).done(function () {
});
}
function onError(reason) {
if (socketsapp.bindingToService) {
socketsapp.listener = null;
socketsapp.bindingToService = false;
}
if (!socketsapp.closing) {
socketsapp.displayStatus(reason);
}
}
})();
Write the following code in the script1.html:
var socketsapp = {};
(function () {
"use strict";
socketsapp.listener = null;
socketsapp.listenerOutputStream = null;
socketsapp.listenerPeerAddress = null;
socketsapp.listenerPeerPort = null;
socketsapp.clientSocket = null;
socketsapp.clientDataWriter = null;
socketsapp.connected = false;
socketsapp.closing = false;
socketsapp.bindingToService = false;
socketsapp.serviceNameAccept = "22112";
socketsapp.hostNameConnect = "localhost";
socketsapp.serviceNameConnect = "22112";
socketsapp.close = function () {
socketsapp.closing = true;
if (socketsapp.listener) {
socketsapp.listener.close();
}
if (socketsapp.clientSocket) {
socketsapp.clientSocket.close();
}
if (socketsapp.clientDataWriter) {
socketsapp.clientDataWriter.close();
}
if (socketsapp.listenerOutputStream) {
socketsapp.listenerOutputStream.close();
}
socketsapp.listener = null;
socketsapp.listenerOutputStream = null;
socketsapp.listenerPeerAddress = null;
socketsapp.listenerPeerPort = null;
socketsapp.clientSocket = null;
socketsapp.clientDataWriter = null;
socketsapp.connected = false;
};
socketsapp.displayStatus = function (message) {
document.getElementById("statusBox").innerHTML = message;
};
socketsapp.displayOutput = function (message) {
document.getElementById("outputBox").innerHTML = message;
};
socketsapp.setValues = function () {
var serviceNameAcceptInput = document.getElementById("serviceNameAccept");
var hostNameConnectInput = document.getElementById("hostNameConnect");
var serviceNameConnectInput = document.getElementById("serviceNameConnect");
if (serviceNameAcceptInput) {
serviceNameAcceptInput.value = socketsapp.serviceNameAccept;
}
if (hostNameConnectInput) {
hostNameConnectInput.value = socketsapp.hostNameConnect;
}
if (serviceNameConnectInput) {
serviceNameConnectInput.value = socketsapp.serviceNameConnect;
}
};
socketsapp.getValues = function (evt) {
switch (evt.target.id) {
case "serviceNameAccept":
socketsapp.serviceNameAccept = evt.target.value;
break;
case "hostNameConnect":
socketsapp.hostNameConnect = evt.target.value;
break;
case "serviceNameConnect":
socketsapp.serviceNameConnect = evt.target.value;
break;
}
};
})();
Output:
Summary
In this article I described how to create a Windows Store App for Datagram Socket Listener using JavaScript. I hope this article has helped you to understand this topic. Please share it. If you know more about this, your feedback and constructive contributions are welcome.