Lesson 1: Communicating by using WebSocket CHAPTER 10 419
function onError(evt) {
writeOutput('ERROR: ' + evt.data);
}
In this example, wsUri is set to the WebSocket.org echo server, which echoes messages
sent to it. The ready function calls the checkSupported function to see whether WebSocket
is supported. This is accomplished by checking whether the window object has a WebSocket
object. If WebSocket is supported, the connect function is called.
The connect function instantiates WebSocket. The constructor accepts a URI argument.
Creating the WebSocket object automatically initiates communications to the URI to attempt
to open the connection asynchronously. The connect function also subscribes to the onopen,
onclose, onmessage, and onerror events. It’s important to subscribe to these events imme-
diately because the connection might open quickly, and you want to ensure that you are
subscribed to the onopen event as soon as possible so you don’t miss the event.
Quick check
■■Can you create a WebSocket object and call the open method when you want to
open a WebSocket connection?
Quick check answer
■■No, there is no open method on the WebSocket object. When you instantiate the
WebSocket object, it automatically attempts to open asynchronously.
The doSend function sends a message to the server. Before sending the message, this
function checks the readyState property of the WebSocket object. The readyState property
contains one of the following values.
■■CONNECTING = 0 Connection is not yet open.
■■OPEN = 1 Connection is open and ready to communicate.
■■CLOSING = 2 Connection is in the process of closing.
■■CLOSED = 3 Connection is closed or couldn’t be opened.
The readyState property will be set to one of the numeric values, but you can use the con-
stants as shown in the doSend function that tests for webSocket.OPEN. If WebSocket is not
open, a message is displayed, and the function returns without sending. If WebSocket is open,
a message is displayed, and the message is sent using the send method.
When a message is received from the server, the onMessage function is called, and the
event object is passed. The data property of the event object contains the message.
When an error is received, the onError function is called, and the event object is passed.
An error can come from the server or be generated when either the client cannot connect
to the server or the connection is timed out. Depending on the error, the event object might
pass the cause on the data property. You might also find that the data property is undefined,
especially in a timeout scenario.