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.

And closing the socket in Scenario 4 is again just a call to StreamSocket.close.<br />

As with the DatagramSocket sample, setting breakpoints within openClient<br />

(js/connectTo-Listener.js), onServerAccept (js/startListener.js), and sendHello (js/sendData.js) will let you<br />

see what’s happening at each step of the process.<br />

Web Sockets: MessageWebSocket and StreamWebSocket<br />

Having now seen both Datagram and Stream sockets in action, we can look at their equivalents on the<br />

WebSocket side. As you might already know, WebSockets is a standard created to use HTTP (and thus<br />

TCP) to set up an initial connection after which the data exchange happens through sockets over TCP.<br />

This provides the simplicity of using HTTP requests for the first stages of communication and the<br />

efficiency of sockets afterwards.<br />

As with regular sockets, the WebSocket side of WinRT supports both water balloons and water hoses:<br />

the MessageWebSocket class provides for discrete packets as with datagram sockets (though it uses TCP<br />

and not UDP), and StreamWebSocket clearly provides for stream sockets. Both classes are very similar to<br />

their respective DatagramSocket and StreamSocket counterparts, so much so that their interfaces are<br />

very much the same (with distinct secondary types like MessageWebSocket-Control):<br />

• Like DatagramSocket, MessageWebSocket has control, information, and outputStream<br />

properties, a messagereceived event, and methods of connectAsync and close. It adds a<br />

closed event along with a setRequestHeader method.<br />

• Like StreamSocket, StreamWebSocket has control, information, inputStream, and<br />

outputStream properties, and methods of connectAsync and close. It adds a closed<br />

event and a setRequestHeader method.<br />

You’ll notice that there isn’t an equivalent to StreamSocketListener here. This is because the process<br />

of establishing that connection is handled through HTTP requests, so such a distinct listener class isn’t<br />

necessary. This is also why we have setRequestHeader methods on the classes above: so that you can<br />

configure those HTTP requests. Along these same lines, you’ll find that the connectAsync methods take a<br />

Windows.Foundation.Uri rather than hostnames and service names. But otherwise we see the same kind<br />

of activity going on once the connection is established, with streams, Data-Reader, and DataWriter.<br />

683

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

Saved successfully!

Ooh no, something went wrong!