HTML and CSS Reference
In-Depth Information
We wrote this example to work with Node.js 0.8. It will not run with earlier versions
of Node.js and may require some modification in the future if the Node APIs change. The
websocket-example module combines the preceding code snippets and some additional
code to form a WebSocket server. This example is not fully robust and production-ready,
but it does serve as a simple, self-contained example of the protocol.
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.
Building a Simple WebSocket Server
Listing 3-6 starts us off by building a simple WebSocket server. You can also open the file
websocket-example.js to view the sample code.
Listing 3-6. WebSocket Server API Written in JavaScript with Node.js
// The Definitive Guide to HTML5 WebSocket
// Example WebSocket server
// See The WebSocket Protocol for the official specification
var events = require("events");
var http = require("http");
var crypto = require("crypto");
var util = require("util");
// opcodes for WebSocket frames
var opcodes = { TEXT : 1
, CLOSE : 8
, PING : 9
, PONG : 10
var WebSocketConnection = function(req, socket, upgradeHead) {
var self = this;
var key = hashWebSocketKey(req.headers["sec-websocket-key"]);
Search WWH ::

Custom Search