51
socket.send("Hello, server!");
The current version of the WebSocket API supports only textual messages, and sends
them as UTF-8 encoded strings. The current WebSocket protocol includes support for
binary messages, however, and a future version of the API may allow binary data to be
exchanged with a WebSocket server.
When your code is done communicating with the server, you can close a WebSocket
by calling its
close()
method.
WebSocket is completely bidirectional, and once a WebSocket connection has been
established, the client and server can send messages to each other at any time, and that
communication does not have to take the form of requests and responses. Each
WebSocket-based service will define its own “subprotocol” for transferring data be-
tween client and server. Over time, these “subprotocols” may evolve, and you may end
up with clients and servers that need to support more than one version of a subprotocol.
Fortunately, the WebSocket protocol includes a negotiation mechanism for choosing
a subprotocol that both client and server can understand. You can pass an array of
strings to the
WebSocket()
constructor. The server will take these as a list of the sub-
protocols that the client understands. It will pick one to use and send it back to the
client. Once the connection is established, the client can determine which subprotocol
is in use by checking the
protocol
property of the socket.
§18.3 explained the EventSource API and demonstrated it with an online chat client
and server. WebSockets make it even easier to write this kind of application. Exam-
ple 22-16 is a very simple chat client: it is a lot like Example 18-15, but it uses a Web-
Socket for bidirectional communication instead of using an EventSource to receive
messages and an XMLHttpRequest to send them.
Example 22-16. A WebSocket-based chat client
<script>
window.onload = function() {
// Take care of some UI details
var nick = prompt("Enter your nickname"); // Get user's nickname
var input = document.getElementById("input"); // Find the input field
input.focus(); // Set keyboard focus
// Open a WebSocket to send and receive chat messages on.
// Assume that the HTTP server we were downloaded from also functions as
// a websocket server, and use the same host name and port, but change
// from the http:// protocol to ws://
var socket = new WebSocket("ws://" + location.host + "/");
// This is how we receive messages from the server through the web socket
socket.onmessage = function(event) { // When a new message arrives
var msg = event.data; // Get text from event object
var node = document.createTextNode(msg); // Make it into a text node
var div = document.createElement("div"); // Create a <div>
div.appendChild(node); // Add text node to div
document.body.insertBefore(div, input); // And add div before input
input.scrollIntoView(); // Ensure input elt is visible
714 | Chapter 22: HTML5 APIs
49
}
// This is how we send messages to the server through the web socket
input.onchange = function() { // When user strikes return
var msg = nick + ": " + input.value; // Username plus user's input
socket.send(msg); // Send it through the socket
input.value = ""; // Get ready for more input
}
};
</script>
<!-- The chat UI is just a single, wide text input field -->
<!-- New chat messages will be inserted before this element -->
<input id="input" style="width:100%"/>
Example 22-17 is a WebSocket-based chat server intended to be run in Node (§12.2).
You can compare this example to Example 18-17 to see that WebSockets simplify the
server-side of the chat application as well as the client-side.
Example 22-17. A chat server using WebSockets and Node
/*
* This is server-side JavaScript, intended to be run with NodeJS.
* It runs a WebSocket server on top of an HTTP server, using an external
* websocket library from https://github.com/miksago/node-websocket-server/
* If it gets an HTTP request for "/" it returns the chat client HTML file.
* Any other HTTP requests return 404. Messages received via the
* WebSocket protocol are simply broadcast to all active connections.
*/
var http = require('http'); // Use Node's HTTP server API
var ws = require('websocket-server'); // Use an external WebSocket library
// Read the source of the chat client at startup. Used below.
var clientui = require('fs').readFileSync("wschatclient.html");
// Create an HTTP server
var httpserver = new http.Server();
// When the HTTP server gets a new request, run this function
httpserver.on("request", function (request, response) {
// If the request was for "/", send the client-side chat UI.
if (request.url === "/") { // A request for the chat UI
response.writeHead(200, {"Content-Type": "text/html"});
response.write(clientui);
response.end();
}
else { // Send a 404 "Not Found" code for any other request
response.writeHead(404);
response.end();
}
});
// Now wrap a WebSocket server around the HTTP server
var wsserver = ws.createServer({server: httpserver});
// Call this function when we receive a new connection request
22.9 Web Sockets | 715
Client-Side
JavaScript
10
wsserver.on("connection", function(socket) {
socket.send("Welcome to the chat room."); // Greet the new client
socket.on("message", function(msg) { // Listen for msgs from the client
wsserver.broadcast(msg); // And broadcast them to everyone
});
});
// Run the server on port 8000. Starting the WebSocket server starts the
// HTTP server as well. Connect to http://localhost:8000/ to use it.
wsserver.listen(8000);
716 | Chapter 22: HTML5 APIs
40
PART III
Core JavaScript Reference
This part of the book is a reference that documents the classes, methods, and properties
defined by the core JavaScript language. This reference is arranged alphabetically by
class or object name:
Arguments EvalError Number
String
Array
Function
Object
SyntaxError
Boolean
Global
RangeError
TypeError
Date
JSON
ReferenceError URIError
Error
Math
RegExp
The reference pages for the methods and properties of classes are alphabetized by their
full names, which include the names of the classes that define them. For example, if
you want to read about the
replace()
method of the String class, you would look under
String.replace()
, not just
replace
.
Core JavaScript defines some global functions and properties, such as
eval()
and
NaN
.
Technically, these are properties of the global object. Since the global object has no
name, however, they are listed in this reference section under their own unqualified
names. For convenience, the full set of global functions and properties in core JavaScript
is summarized in a special reference page named “Global” (even though there is no
object or class by that name).
34
Core JavaScript Reference
arguments[ ]
an array of function arguments
Synopsis
arguments
Description
The
arguments[]
array is defined only within a function body. Within the body of a function,
arguments
refers to the Arguments object for the function. This object has numbered proper-
ties and serves as an array containing all arguments passed to the function. The
arguments
identifier is essentially a local variable automatically declared and initialized within every
function. It refers to an Arguments object only within the body of a function and is undefined
in global code.
See Also
Arguments
; Chapter 8
Arguments
arguments and other properties of a function
Object → Arguments
Synopsis
arguments
arguments[n]
Elements
The Arguments object is defined only within a function body. Although it is not technically
an array, the Arguments object has numbered properties that function as array elements and
a
length
property that specifies the number of array elements. Its elements are the values that
are passed as arguments to the function. Element 0 is the first argument, element 1 is the
second argument, and so on. All values passed as arguments become array elements of the
719
49
Arguments object, whether or not those arguments are given names in the function
declaration.
Properties
callee
A reference to the function that is currently executing.
length
The number of arguments passed to the function and the number of array elements in
the Arguments object.
Description
When a function is invoked, an Arguments object is created for it, and the local variable
arguments
is automatically initialized to refer to that Arguments object. The main purpose of
the Arguments object is to provide a way to determine how many arguments are passed to
the function and to refer to unnamed arguments. In addition to the array elements and
length
property, however, the
callee
property allows an unnamed function to refer to itself.
For most purposes, the Arguments object can be thought of as an array with the addition of
the
callee
property. However, it is not an instance of Array, and the
Arguments.length
prop-
erty does not have any of the special behaviors of the
Array.length
property and cannot be
used to change the size of the array.
In non-strict mode, the Arguments object has one very unusual feature. When a function has
named arguments, the array elements of the Arguments object are synonyms for the local
variables that hold the function arguments. The Arguments object and the argument names
provide two different ways of referring to the same variable. Changing the value of an argu-
ment with an argument name changes the value that is retrieved through the Arguments
object, and changing the value of an argument through the Arguments object changes the
value that is retrieved by the argument name.
See Also
Function
; Chapter 8
Arguments.callee
not defined in strict mode
the function that is currently running
Synopsis
arguments.callee
Description
arguments.callee
refers to the function that is currently running. It provides a way for an
unnamed function to refer to itself. This property is defined only within a function body.
Arguments.callee
720 | Core JavaScript Reference
50
Example
// An unnamed function literal uses the callee property to refer
// to itself so that it can be recursive
var factorial = function(x) {
if (x < 2) return 1;
else return x * arguments.callee(x-1);
}
var y = factorial(5); // Returns 120
Arguments.length
the number of arguments passed to a function
Synopsis
arguments.length
Description
The
length
property of the Arguments object specifies the number of arguments passed to
the current function. This property is defined only within a function body.
Note that this property specifies the number of arguments actually passed, not the number
expected. See
Function.length
for the number of declared arguments. Note also that this
property does not have any of the special behavior of the
Array.length
property.
Example
// Use an Arguments object to check that correct # of args were passed
function check(args) {
var actual = args.length; // The actual number of arguments
var expected = args.callee.length; // The expected number of arguments
if (actual != expected) { // Throw exception if they don't match
throw new Error("Wrong number of arguments: expected: " +
expected + "; actually passed " + actual);
}
}
// A function that demonstrates how to use the function above
function f(x, y, z) {
check(arguments); // Check for correct number of arguments
return x + y + z; // Now do the rest of the function normally
}
See Also
Array.length
,
Function.length
Array
built-in support for arrays
Object → Array
Array
Core JavaScript Reference | 721
Core JavaScript
Reference
82
Constructor
new Array()
new Array(size)
new Array(element0, element1, ..., elementn)
Arguments
size
The desired number of elements in the array. The returned array has its
length
field set
to
size
.
element0, ... elementn
An argument list of two or more arbitrary values. When the
Array()
constructor is in-
voked with these arguments, the newly created array is initialized with the specified ar-
gument values as its elements and its
length
field set to the number of arguments.
Returns
The newly created and initialized array. When
Array()
is invoked with no arguments, the
returned array is empty and has a
length
field of 0. When invoked with a single numeric
argument, the constructor returns an array with the specified number of undefined elements.
When invoked with any other arguments, the constructor initializes the array with the values
specified by the arguments. When the
Array()
constructor is called as a function, without the
new
operator, it behaves exactly as it does when called with the
new
operator.
Throws
RangeError
When a single integer
size
argument is passed to the
Array()
constructor, a
RangeError
exception is thrown if
size
is negative or is larger than 232−1.
Literal Syntax
ECMAScript v3 specifies an array literal syntax. You may also create and initialize an array
by placing a comma-separated list of expressions within square brackets. The values of these
expressions become the elements of the array. For example:
var a = [1, true, 'abc'];
var b = [a[0], a[0]*2, f(x)];
Properties
length
A read/write integer specifying the number of elements in the array or, when the array
does not have contiguous elements, a number one larger than the index of the last element
in the array. Changing the value of this property truncates or extends the array.
Methods
The methods
every()
,
filter()
,
forEach()
,
indexOf()
,
lastIndexOf()
,
map()
,
reduce()
,
reduce
Right()
, and
some()
are new in ECMAScript 5 but were implemented by browsers other than
IE before ES5 was standardized.
Array
722 | Core JavaScript Reference
Documents you may be interested
Documents you may be interested