HTML and CSS Reference
In-Depth Information
how messages work with the API, the WebSocket API only exposes complete messages,
not WebSocket frames. The message event fires when messages are received. The
corresponding callback to the message event is called onmessage .
Listing 2-5 shows a message handler receiving a text message and displaying the
content of the message.
Listing 2-5. Sample Message Event Handler for Text Messages
// Event handler for receiving text messages
ws.onmessage = function(e) {
if(typeof e.data === "string"){
console.log("String message received", e, e.data);
} else {
console.log("Other message received", e, e.data);
}
};
In addition to text, WebSocket messages can handle binary data, which are handled
as Blob messages, as shown in Listing 2-6 or as ArrayBuffer messages, as shown in
Listing 2-7. Because the application setting for the WebSocket message binary data type
affects incoming binary messages, you must decide the type you want to use for incoming
binary data on the client before reading the data.
Listing 2-6. Sample Message Event Handler for Blob Messages
// Set binaryType to blob (Blob is the default.)
ws.binaryType = "blob";
// Event handler for receiving Blob messages
ws.onmessage = function(e) {
if(e.data instanceof Blob){
console.log("Blob message received", e.data);
var blob = new Blob(e.data);
}
};
Listing 2-7 shows a message handler checking and handling for ArrayBuffer messages.
Listing 2-7. Sample Message Event Handler for ArrayBuffer Messages
// Set binaryType to ArrayBuffer messages
ws.binaryType = "arraybuffer";
// Event handler for receiving ArrayBuffer messages
ws.onmessage = function(e) {
if(e.data instanceof ArrayBuffer){
console.log("ArrayBuffer Message Received", + e.data);
// e.data is an ArrayBuffer. Create a byte view of that object.
var a = new Uint8Array(e.data);
}
};
 
Search WWH ::




Custom Search