HTML and CSS Reference
In-Depth Information
Implementing RFB in JavaScript
The client side of this RFB application is an HTML5 application that runs in the browser.
It makes use of HTML, CSS, and JavaScript. The basic user interface is defined by some
HTML markup. The logic of the application, including a library to communicate using the
RFB protocol, is written in JavaScript.
Listing 6-2 shows the starting HTML that includes the protocol library and
application scripts:
Listing 6-2. Starting HTML with Protocol Library and Application Scripts
<!DOCTYPE html>
<title>RFB over WebSocket</title>
<script src="bytes.js"></script>
<script src="RfbClient.js"></script>
<script src="ui.js"></script>
because JavaScript is purely event-driven, there is no way to wait inside of a
running function for more bytes to become available. Every function must run to completion
and return quickly. To enable a JavaScript application to receive RFb protocol messages,
we map the protocol to event handlers that can run in the browser. This design technique is
useful for implementing many different types of protocols.
Pro Tip
Working with Byte Streams
In Chapter 2, we demonstrated how to send and receive binary data with the WebSocket
API. Writing binary messages is as simple as calling WebSocket.send() with Blob and
ArrayBuffer arguments. Reading binary messages is automatic, as the type of incoming
message events matches WebSocket.binaryType . It is straightforward to communicate
using WebSocket messages using the WebSocket API, and to implement protocols with a
message-aligned binding to the WebSocket Protocol. In contrast, arbitrary application-level
protocols like RFB are not aligned to WebSocket frames. The syntax of such a protocol is
defined in terms of streams of bytes. Each call to WebSocket.onmessage is not guaranteed
to contain one and only one complete RFB message. RFB messages can be fragmented or
conflated into more or fewer than the expected number of WebSocket messages. A stream
abstraction can be useful to bridge the gap between the two modes of communication.
In Listing 6-3, the file bytes.js contains utilities used by RfbClient.js to simplify
reading and writing byte streams. In particular, it contains a CompositeStream API that
joins sequences of discrete ArrayBuffers into logical streams of bytes. When binary
WebSocket messages arrive, RfbClient.js calls CompositeStream.append() to add
the new bytes to the inbound stream. To read and parse messages at the RFB protocol
level, RFB handler code calls CompositeStream.consume() to pull bytes out of the
stream. Similarly, RfbClient.js uses functions in bytes.js to write numbers as bytes in
messages to the server. These functions make use of the standard DataView type, calling
 
 
Search WWH ::




Custom Search