HTML and CSS Reference
In-Depth Information
socket.onclose = function() {
// WebSocket has been closed
};
socket.onerror = function(event) {
// Error triggered
};
To send data on the socket, call
socket.send
:
socket.send(message);
This sends the message string to the server. One thing to remember with WebSockets is that all the data sent
back and forth is in the form of a string, so it's up to you to encode and decode those strings with some mech-
anism. (JSON is an obvious and popular choice.)
Rather than set up a server simply to test out native WebSockets, the
websocket.org
website provides an echo
server you can use to test writing the client-side WebSocket code.
Create a new file called
echo.html
and add the code in
Listing 21-1
to it.
Listing 21-1:
A simple echo-server client
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/
↵
ajax/libs/jquery/1.7.2/jquery.min.js" ></script>
<title>WebSocket Test</title>
</head>
<body>
<script>
var echoURI = "ws://echo.websocket.org/";
var socket;
$(function() {
socket = new WebSocket(echoURI);
socket.onopen = function() {
$("#output").append("<div>WebSocket Opened</div>");
};
socket.onclose = function() {
$("#output").append("<div>WebSocket Opened</div>");
};
socket.onmessage = function(event) {
$("#output").append("<div>WebSocket Message:" +
event.data + "</div>");
};
socket.onerror = function() {
$("#output").append("<div>WebSocket Error</div>");