HTML and CSS Reference
In-Depth Information
// Attempt to send update every second.
setInterval( function() {
// Send only if the buffer is not full
if (ws.bufferedAmount < THRESHOLD) {
ws.send(getApplicationState());
}
}, 1000);
};
Using the bufferedAmount attribute can be useful for throttling the rate at which
applications send data to the server avoiding network saturation.
You may want to examine the WebSocket object's bufferedAmount attribute
before attempting to close the connection to determine if any data has yet to be transmitted
from the application.
Pro Tip
WebSocket Object Attribute: protocol
In our previous discussion about the WebSocket constructor, we mentioned the protocol
argument that lets the server know which protocol the client understands and can use
over WebSocket. The WebSocket object protocol attribute provides another piece of
useful information about the WebSocket instance. The result of protocol negotiation
between the client and the server is visible on the WebSocket object. The protocol
attribute contains the name of the protocol chosen by the WebSocket server during the
opening handshake. In other words, the protocol attribute tells you which protocol to
use with a particular WebSocket. The protocol attribute is the empty string before the
opening handshake completes and remains an empty string if the server does not choose
one of the protocols offered by the client.
Putting It All Together
Now that we've walked through the WebSocket constructor, events, attributes, and
methods, let's put together what we have learned about the WebSocket API. Here, we
create a client application to communicate with a remote server over the Web and
exchange data using WebSocket. Our sample JavaScript client uses the “Echo” server
hosted at ws://echo.websocket.org , which receives and returns any message you send
to the server. Using an Echo server can be useful for pure client-side testing, particularly
for understanding how the WebSocket API interacts with the server.
First, we create the connection, then display on a web page the events triggered by
our code, which come from the server. The page will display information about the client
connecting to the server, sending and receiving messages to and from the server, then
disconnecting from the server.
Listing 2-18 shows a complete example of communication and messaging with
the server.
 
 
Search WWH ::




Custom Search