HTML and CSS Reference
for sending and receiving files, mostly multimedia files, images, video, and audio. The
sample code at the end of this chapter uses the WebSocket API in conjunction with the
File API, reads the content of a file, and sends it as a WebSocket message.
WebSocket Method: close()
To close the WebSocket connection or to terminate an attempt to connect, use the
close() method. If the connection is already closed, then the method does nothing. After
calling close() , you cannot send any more data on the closed WebSocket. Listing 2-15
shows an example of the close() method:
Listing 2-15. Calling the close() Method
// Close the WebSocket connection
You can optionally pass two arguments to the close() method: code (a numerical
status code) and reason (a text string). Passing these arguments transmits information
to the server about why the client closed the connection. We will discuss the status
codes and reasons in greater detail in Chapter 3, when we cover the WebSocket closing
handshake. Listing 2-16 shows an example of calling the close() method with an
Listing 2-16. Calling the close() Method with a Reason
// Close the WebSocket connection because the session has ended successfully
ws.close(1000, "Closing normally");
Listing 2-16 uses code 1000, which means, as it states in the code, that the
connection is closing normally.
WebSocket Object Attributes
There are several WebSocket Object attributes you can use to provide more information
about the WebSocket object: readyState , bufferedAmount , and protocol .
WebSocket Object Attribute: readyState
The WebSocket object reports the state of the connection through the read-only attribute
readyState , which you've already learned a bit about in the previous sections. This
attribute automatically changes according to the connection state, and provides useful
information about the WebSocket connection.
Table 2-1 describes the four different values to which the readyState attribute can
be set to describe connection state.