HTML and CSS Reference
In-Depth Information
Listing 2-18. Complete Client Application Using the WebSocket API
<!DOCTYPE html>
<title>WebSocket Echo Client</title>
<h2>Websocket Echo Client</h2>
<div id="output"></div>
<script>
// Initialize WebSocket connection and event handlers
function setup() {
output = document.getElementById("output");
ws = new WebSocket(" ws://echo.websocket.org/echo ");
// Listen for the connection open event then call the sendMessage function
ws.onopen = function(e) {
log("Connected");
sendMessage("Hello WebSocket!")
}
// Listen for the close connection event
ws.onclose = function(e) {
log("Disconnected: " + e.reason);
}
// Listen for connection errors
ws.onerror = function(e) {
log("Error ");
}
// Listen for new messages arriving at the client
ws.onmessage = function(e) {
log("Message received: " + e.data);
// Close the socket once one message has arrived.
ws.close();
}
}
// Send a message on the WebSocket.
function sendMessage(msg){
ws.send(msg);
log("Message sent");
}
// Display logging information in the document.
function log(s) {
var p = document.createElement("p");
p.style.wordWrap = "break-word";
 
Search WWH ::




Custom Search