HTML and CSS Reference
In-Depth Information
Listing 2-11 will not work because the connection is not yet open. Instead, you
should wait for the open event before sending your first message on a newly constructed
WebSocket, as shown in Listing 2-12.
Listing 2-12. Waiting for the Open Event Before Sending a Message
// Wait until the open event before calling send().
var ws = new WebSocket(" ws://echo.websocket.org " )
ws.onopen = function(e) {
ws.send("Initial data");
}
If you want to send messages in response another event, you can check the
WebSocket readyState property and choose to send the data only while the socket is
open, as shown in Listing 2-13.
Listing 2-13. Checking the readyState Property for an Open WebSocket
// Handle outgoing data. Send on a WebSocket if that socket is open.
function myEventHandler(data) {
if (ws.readyState === WebSocket.OPEN) {
// The socket is open, so it is ok to send the data.
ws.send(data);
} else {
// Do something else in this case.
//Possibly ignore the data or enqueue it.
}
}
In addition to the text (string) messages, the WebSocket API allows you to send
binary data, which is especially useful to implement binary protocols. Such binary
protocols can be standard Internet protocols typically layered on top of TCP, where the
payload can be either a Blob or an ArrayBuffer. Listing 2-14 is an example of how you can
send a binary message over WebSocket.
Note
Chapter 6 shows an example of how you can send binary data over WebSocket.
Listing 2-14. Sending a Binary Message Over WebSocket
// Send a Blob
var blob = new Blob("blob contents");
ws.send(blob);
// Send an ArrayBuffer
var a = new Uint8Array([8,6,7,5,3,0,9]);
ws.send(a.buffer);
 
 
Search WWH ::




Custom Search