23.01.2018 Views

MICROSOFT_PRESS_EBOOK_PROGRAMMING_WINDOWS_8_APPS_WITH_HTML_CSS_AND_JAVASCRIPT_PDF

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

try {<br />

var size = dataWriter.measureString(data);<br />

countOfDataSent += size;<br />

}<br />

dataWriter.writeString(data);<br />

dataWriter.storeAsync().done(function () {<br />

// Add a 1 second delay so the user can see what's going on.<br />

setTimeout(writeOutgoing, 1000);<br />

}, writeError);<br />

}<br />

catch (error) {<br />

// [Output error message]<br />

}<br />

function readIncoming(args) {<br />

// Buffer as much data as you require for your protocol.<br />

dataReader.loadAsync(100).done(function (sizeBytesRead) {<br />

countOfDataReceived += sizeBytesRead;<br />

// [Output count]<br />

var incomingBytes = new Array(sizeBytesRead);<br />

dataReader.readBytes(incomingBytes);<br />

// Do something with the data. Alternatively you can use DataReader to<br />

// read out individual booleans, ints, strings, etc.<br />

}<br />

// Start another read.<br />

readIncoming();<br />

}, readError);<br />

function onClosed(args) {<br />

// [Other code omitted, including closure of DataReader and DataWriter]<br />

streamWebSocket.close();<br />

}<br />

As with regular sockets, you can exercise additional controls with WebSockets, including setting<br />

credentials and indicating supported protocols through the control property of both MessageWeb-Socket<br />

and StreamWebSocket. For details, see How to use advanced WebSocket controls in the documentation.<br />

Similarly, you can set up a secure/encrypted connection by using the wss:// URI scheme instead of<br />

ws:// as used in the sample. For more, see How to secure WebSocket connections with TLS/SSL.<br />

The ControlChannelTrigger Background Task<br />

In Chapter 13, in the “Lock Screen Dependent Tasks and Triggers” section we took a brief look at the<br />

Windows.Networking.Sockets.ControlChannelTrigger class that can be used to set up a background<br />

task for real-time notifications as would be used by VoIP, IM, email, and other “always reachable”<br />

scenarios. To repeat, working with the control channel is not something that can be done<br />

from JavaScript, so refer to How to set background connectivity options in the documentation along<br />

with the following C#/C++ samples:<br />

687

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!