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 :
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 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
<html lang="en">
<meta charset="UTF-8">
<script src="
ajax/libs/jquery/1.7.2/jquery.min.js" ></script>
<title>WebSocket Test</title>
var echoURI = "ws://";
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:" + + "</div>");
socket.onerror = function() {
$("#output").append("<div>WebSocket Error</div>");
Search WWH ::

Custom Search