[HTML5 API] Web Sockets

Web socket

Features of the HTTP protocol: It is a stateless protocol consisting of client requests and server responses. HTTP is actually a relatively special network protocol. Most Internet-based (or LAN-based) network connections usually include long connections and two-way message exchange over TCP sockets. It is not safe for untrusted client scripts to access the underlying TCP socket, but the WebSocket API defines a security scheme that allows client code to create two-way socket-type connections on the client side and on the server side that supports the WebSocket protocol. This makes some network operations easier.

The WebSocket API is very simple to use. First, create a socket through the WebSocket() constructor:

var socket = new WebSocket("ws://ws.example.com:1234/resource");

The parameter to the WebSocket() constructor is a URL that uses the ws://protocol (or a wss://protocol similar to https://for secure links). The URL specifies the host to connect to, and possibly the port (the WebSocket uses the default port like HTTP and HTTPS) and the path or resource.

After creating a socket, you usually need to register an event handler on it:

socket.onopen = function(e) { /* Socket is already connected */ };
socket.onclose = function(e) { /* The socket is closed.*/ };
socket.onerror = function(e) { /* Error */ };
socket.onmessage = function(e) {
 var message = e.data; /*The server sends a message*/
};

In order to send data to the server through a socket, the send() method of the socket can be called:

socket.send("Hello, server!");

The current version of the WebSocket API only supports text messages and must be passed to it as UTF-8 encoded strings. However, the current WebSocket protocol also includes support for binary messages, and future versions of the API may allow the exchange of binary data between the client and the WebSocket server.

When communication with the server is complete, you can close the WebSocket by calling the close() method.

WebSockets are completely bidirectional, and once a WebSocket connection is established, both client and server sides can transmit messages to each other at any time, at the same time, this communication mechanism is not in the form of requests and responses. Each WebSocket-based service defines its own "sub-protocol" for data transfer on both the client and server sides. Slowly, these "sub-protocols" may also evolve and may ultimately require that both client and server sides support multiple versions of the sub-protocols. Fortunately, the WebSocket protocol contains a negotiation mechanism for selecting subprotocols that both client and server sides can "understand". You can pass an array of strings to the WebSocket() constructor. The server side uses this array as a list of subprotocols that the client understands. It then selects one of the uses and passes it to the client. Once the connection is established, the client can detect which seed protocol is currently in use through the protocol property of the socket.

An example is a simple chat client: it uses a WebSocket for two-way communication instead of EventSource for getting messages and XMLHttpRequest for sending messages.

Example: Based on WebSocket Chat Client for

<script>
window.onload = function() {
    // Care about some UI details
    var nick = prompt("Enter your nickname");         // Get User Nicknames 
    var input = document.getElementById("input");     // Find input Field 
    input.focus();	                                  // Set cursor
    
    // Open a WebSocket to send and receive chat messages
    // Suppose the downloaded HTTP server operates as a WebSocket server and uses the same host name and port 
    // Just protocol changed from htttp://to ws://
    var socket = new WebSocket("ws://" + location.host + "/");
    
    // The following shows how to get messages from the server using a WebSocket
    socket.onmessage = function(event) {             // When a message is received
        var msg = event.data;                        // Get message content from event object
        var node = document.createTextNode(msg);     // Mark it as a text node
        var div = document.createElement("div");     // Create a <div>
        div.appendChild(node);                       // Add a text node to the div
        document.body.insertBefore(div, input);      // Add the div before input
        input.scrollIntoView();                      // Make sure the input box is visible
    }
    
    // The following shows how to send messages to the server through a WebSocket
    input.onchange = function() {                    // When the user hit the Enter key 
        var msg = nick + ": " + input.value;         // User nickname plus user input
        socket.send(msg);                            // Pass this through a socket
        input.value = "";                            // Waiting for more input
    }
};
</script>
<!-- Chat window UI Simple, a wide text input field --> 
<!-- New chat messages are inserted into this element -->
<input id="input" style="width:100%"/> 

The following example is a WebSocket-based chat server running in Node. WebSocket simplifies the service side of a chat application to be the same as the client side.

example: Use WebSocket and Node Chat Server for
/*
 * This is server-side JavaScript running on NodeJS
 * On top of the HTTP server, it runs a WebSocket server that wants to come from
 * https://github.com/miksago/node-websocket-server/ Third-party WebSocket library implementation
 * If you get an HTTP request for'/', return the HTML file of the chat client
 * Any other HTTP request returns 404
 * Messages received through the WebSocket protocol are broadcast only to all active connections
 */
var http = require('http');	              // HTTP Server API using Node
var ws = require('websocket-server');     // Use third-party WebSocket Libraries

// Start-up phase, read resource files of chat clients
var clientui = require('fs').readFileSync("wschatclient.html");

// Create an HTTP server
var httpserver = new http.Server();

// Run this function when the HTTP server receives a new request
httpserver.on("request", function (request, response) {
    // Return to client chat UI if'/'is requested
    if (request.url === "/") { // Request Chat UI
        response.writeHead(200, ("Content-Type": "text/html"}); 
        response.write(clientui);
        response.end();
    }
    
    else { //Return 404 "Not Found" encoding for any other request
        response.writeHead(404);
        response.end();
    }
});

// Wrapping a WebSocket server on an HTTP server
var wsserver = ws.createServer({server: httpserver});

// Call this function when a new connection request is received
wsserver.on ("connection**, function(socket) (
    socket.send("Welcome to the chat room.");     // Greet new clients 
    socket.on("message", function(msg) {	     // Listen for messages from clients
        wsserver. broadcast (msg);	              // And broadcast them to everyone
    });
});

// Run the server on port 8000. The HTTP server is also started when the WebSocket server is started 
// connection to http://localhost:8000/ And start using it
wsserver.listen(8000);

Tags: Javascript Front-end

Posted on Wed, 24 Nov 2021 13:55:02 -0500 by d_mc_a