Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Communicating by using WebSocket CHAPTER 10 417


■■binaryType A property that indicates the binary data format the onmessage event
receives.
■■bufferedAmount A property containing the number of data bytes queued using the
send method.
■■extensions A property that indicates the extensions the server selected.
■■onclose An event property that’s called when the socket is closed.
■■onerror An event property that’’s called when there is an error.
■■onmessage An event property that’s called when a message is received.
■■onopen An event property that’s called when WebSocket establishes a connection.
■■protocol A property that indicates the protocol that the server selected.
■■readyState A property that indicates the state of the WebSocket connection.
■■url A property that indicates the current URL of the WebSocket object.

Implementing the WebSocket object


WebSocket protocol communications typically use TCP port number 80, so environments that
block non-standard Internet connections by using a firewall will still pass WebSocket packets.
In the following example, a webpage is created that calls the WebSocket.org echo server,
which will return the message passed to it. Consider the following webpage that contains a
text box for entering a message and a button to send the message to a server; all output is
appended to the <div> element whose id is divOutput.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.8.2.js"></script>
<script src="Scripts/default.js"></script>
</head>
<body>
<h2>WebSocket Test</h2>
Enter Message: <input type="text" id="txtMessage" />
<button type="button" id="btnSend">Send</button><br />
<div id="divOutput"></div>
</body>
</html>

Whereas an HTTP URL begins with http:// or https:// for secure HTTP, the WebSocket URL
begins with ws:// or wss:// for secure WebSocket protocol. In the browser code, you create a
WebSocket object and configure the onopen, onmessage, onerror, and onclose events. Call
the send method to send a message, and the onmessage event triggers if there is a response.
The default.js file contains the following.
/// <reference path="_references.js" />
var wsUri = 'ws://echo.websocket.org/';
Free download pdf