Java Reference
In-Depth Information
14.2. Introducing WebSockets
WebSockets are the solution to implementing truly asynchronous communication in web
applications without using plug-ins, AJAX polling, or custom Comet solutions. It's stand-
ardized and part of HTML5, meaning that all browsers, including mobile browsers, must
support it. Because it rests on top of HTTP and has a standard protocol, firewall and
browser support is well defined. WebSockets also benefit from Web Worker, another part of
HTML5. Web Workers for the first time give JavaScript rudimentary multithreading sup-
port, which is a necessity for asynchronous communication.
Let's dive into WebSockets further so that the Java EE 7 support will make more sense. If
you've already mastered WebSockets, feel free to jump ahead to the next section.
To better understand WebSockets, we'll first examine the technology in the context of
HTML5 without discussing the server component. We'll look at the basics of the protocol
as well as how you interact with WebSockets from JavaScript. After you have a handle on
the technology from a pure HTML5 perspective, we'll then compare it to AJAX and Co-
met. Although AJAX is still relevant and indeed useful, you'll see why WebSockets is a
much better solution than Comet.
14.2.1. WebSockets basics
WebSockets are a new transport technology that uses HTTP. A connection starts out using
HTTP or HTTPS and is then upgraded to a WebSocket connection using a handshake. We-
bSockets use HTTP/HTTPS so that existing infrastructure can be reused. Both HTTP and
HTTPS are well understood by server-side software and intermediate infrastructure, such
as firewalls and proxies. WebSockets are thus backward-compatible with existing network
infrastructure. You don't have to have additional ports on a firewall opened or upgrade
proxy firewalls.
Opening a WebSocket connection in the browser involves passing a URL using the We-
bSocket scheme to the WebSocket constructor. Here's an example JavaScript snippet to
open a connection to the ActionBazaar support chat service:
var webSocket = new WebSocket('ws://127.0.0.1:8080/chapter14/chat');
Search WWH ::




Custom Search