HTML and CSS Reference
In-Depth Information
The close event has three useful properties you can use for error handling and
recovery: wasClean , code , and error . The wasClean property is a boolean indicating
whether the connection was closed cleanly. The property is true if the WebSocket closed
in response to a close frame from the server. If the connection closes due to some other
reason (for example, because underlying TCP connection closed), the wasClean property
is false . The code and reason properties indicate the status of the closing handshake
conveyed from the server. These properties are symmetrical with the code and reason
arguments given in the WebSocket.close() method, which we'll describe in detail later
in this chapter. In Chapter 3, we will cover the closing codes and their meanings as we
discuss the WebSocket Protocol.
For more details about WebSocket events, see the WebSocket API specification at
http://www.w3.org/TR/websockets/ .
Note
WebSocket Methods
WebSocket objects have two methods: send() and close() .
WebSocket Method: send()
Once you establish a full-duplex, bidirectional connection between your client and server
using WebSocket, you can invoke the send() method while the connection is open (that
is, after the onopen listener is called and before the onclose listener is called). You use
the send() method to send messages from your client to the server. After sending one
or more messages, you can leave the connection open or call the close() method to
terminate the connection.
Listing 2-10 is an example of how you can send a text message to the server.
Listing 2-10. Sending a Text Message Over WebSocket
// Send a text message
ws.send("Hello WebSocket!");
The send() method transmits data when the connection is open. If the connection
is not available or closed, it throws an exception about the invalid connection state.
A common mistake people make when starting out with the WebSocket API is attempting
to send messages before the connection is open, as shown in Listing 2-11.
Listing 2-11. Attempting to Send Messages Before Opening a Connection
// Open a connection and try to send a message. (This will not work!)
var ws = new WebSocket(" ws://echo.websocket.org " )
ws.send("Initial data");
 
 
Search WWH ::




Custom Search