HTML and CSS Reference
The WebSocket Object
The HTML5 WebSocket object provides properties, methods, and events that you can use to develop a Web
Socket client application. Table 11-4 shows them for your quick reference.
Table 11-4. Properties, Methods, and Events of the WebSocket Class
Property / Method /
Read-only property that returns the current state of the
connection. Possible values are 0 ( CONNECTING ), 1 ( OPEN ), 2
( CLOSING ), and 3 ( CLOSED ).
Read-only property that returns the number of bytes of data that
have been queued for transmission over the network.
Sends data to the Web Socket server over an established
Closes the previously established connection with the Web Socket
Raised when the readyState property changes to 1 ( OPEN ) and
indicates that the connection is ready to send and receive data.
Raised when the readyState property changes to 3 ( CLOSED ).
Raised when a message is received from the Web Socket server.
Raised when an error occurs during communication with the Web
When you create an instance of WebSocket , you need to supply the endpoint URL that connects the
client to the Web Socket server. As you can see from Table 11-4, the data-sending and -receiving pattern
used by WebSocket is similar to earlier techniques. Once a connection is established, you send data using
send() as and when required. At the same time, the message event-handler function keeps receiving
messages sent by the server.
Using WebSocket in ASP.NET
As mentioned earlier, while developing a Web Socket application you have two distinct pieces of code: the
HTML5 WebSocket object. So, this piece of code follows the same coding pattern regardless of your web
server software. However, when you're developing the Web Socket server, you need to use the framework
provided by the web server software and the server-side framework you're using. As far as ASP.NET is
concerned, IIS 8 and certain .NET framework classes together allow you to develop a Web Socket server.
To understand how the client-side and server-side code go hand in hand, let's develop a simple Echo
server that echoes whatever the client sends to it. Although the Echo server doesn't perform simultaneous
two-way communication like a chat application, it does illustrate how the Web Socket client and server
interact. The web form that acts as a Web Socket client is shown in Figure 11-9.