HTML and CSS Reference
In-Depth Information
Using HTML5 Media with WebSocket
As part of HTML5 and the Web platform, the WebSocket API was designed to work well
with all HTML5 features. The data types that you can send and receive with the API are
broadly useful for transferring application data and media. Strings, of course, allow you to
represent web data formats like XML and JSON. The binary types integrate with APIs like
drag-and-drop, FileReader, WebGL, and the Web Audio API.
Let's take a look at using HTML5 media with WebSocket. Listing 2-20 shows a
complete client application using HTML5 Media with WebSocket. You can create your
own HTML file based on this code.
To build (or simply follow) the examples in this topic, you can choose to use the
virtual machine (VM) we've created that contains all the code, libraries, and servers we use
in our examples. Refer to Appendix b for instructions on how to download, install, and start
the VM.
Note
Listing 2-20. Complete Client Application Using HTML5 Media with WebSocket
<!DOCTYPE html>
<title>WebSocket Image Drop</title>
<h1>Drop Image Here</h1>
<script>
// Initialize WebSocket connection
var wsUrl = " ws://echo.websocket.org/echo " ;
var ws = new WebSocket(wsUrl);
ws.onopen = function() {
console.log("open");
}
// Handle binary image data received on the WebSocket
ws.onmessage = function(e) {
var blob = e.data;
console.log("message: " + blob.size + " bytes");
// Work with prefixed URL API
if (window.webkitURL) {
URL = webkitURL;
}
var uri = URL.createObjectURL(blob);
var img = document.createElement("img");
img.src = uri;
document.body.appendChild(img);
}
 
 
Search WWH ::




Custom Search