HTML and CSS Reference
In-Depth Information
method will be suspended until the awaited task completes. In this case, the awaited task is to receive
incoming data and store it in an
ArraySegment
, a byte array. The results of the receive operation are stored
in a
WebSocketReceiveResult
object.
If the
WebSocket
is open, as indicated by the
State
property, the received data is echoed to the client
using the
SendAsync()
method. Before sending the message back to the client, you append a date-time
stamp to the message. If the
State
property has any value other than
Open
, the
while
loop is exited, thus
terminating the server.
n
Note
The
System.Net.WebSockets
and
System.Web.WebSockets
namespaces contain classes that deal
with server-side Web Socket programming. Detailed discussion of asynchronous programming in .NET and using
Web Socket classes is beyond the scope of this topic. Refer to the MSDN documentation to learn more about these
topics.
Developing the Web Socket Client
Now that you've completed the Echo server, let's develop the client web form that sends data to the Echo
server and receives echoed messages. Listing 11-17 shows the jQuery code that uses the HTML5
WebSocket
object.
Listing 11-17.
Using the HTML5
WebSocket
Object
var socket;
$(document).ready(function () {
if (!Modernizr.websockets) {
alert(“This browser doesn't support HTML5 Web Sockets!”);
return;
}
socket = new WebSocket(“ws://localhost:49428/WebSocketGenericHandler.ashx”);
socket.addEventListener(“open”, function (evt) {
$(“#divHistory”).append('<h3>Connection Opened with the Echo server.</h3>');
}, false);
socket.addEventListener(“message”, function (evt) {
$(“#divHistory”).append('<h3>' + evt.data + '</h3>');
}, false);
socket.addEventListener(“error”, function (evt) {
$(“#divHistory”).append('<h3>Unexpected Error.</h3>');
}, false);
…
});
This code declares a global variable named
socket
to hold a reference to a
WebSocket
object. The
jQuery
ready()
method first checks whether HTML5 Web Sockets are supported in the client browser. It
does so using the Modernizr's
websockets
property.
You then create a
WebSocket
instance by passing the URL of
WebSocketGenericHandler.ashx
. Notice
how the URL uses
ws://
instead of
http://
. Next, event handlers for the three events—
open
,
message
, and
error
—are wired using the
addEventListener()
method. In the
message
event handler, the data sent by the
Echo server is retrieved using the
evt.data
property. The echoed data is then appended to a
<div>
element.
The other event handlers output the specified messages in the
<div>
element.