How WebSockets function and are utilized

WebSocket is a sophisticated technology that enables browser-to-server bidirectional communication. Thanks to this protocol, it is possible to send a request to the server and receive a response in the form of events, so eliminating the need to resend the request. WebSockets offer a variety of advantages and can be utilized in numerous projects. Discover why you should use this technology and how to do it.

php
php coding
javascript
socket.io with php

how it functions

Websockets is a web technology that permits bidirectional, real-time communication between a web client and a web server. It is compatible with modern web browsers because it conforms to the HTML5 standard (including Internet Explorer 10 and its latest versions).

To provide full support for legacy solutions, every connection begins with HTTP. Web client sends a request to the server, and if the server supports WebSockets, it sends a response that overwrites the connection header. A WebSockets-based connection has been established at this time.

lightning-fast websockets

According to a number of tests, the WebSockets protocol is three times faster than HTTP, which increases the rate of data flow between apps. One of the greatest benefits of utilizing WebSockets is that it does not interfere with firewalls and proxy servers, which plagued most other solutions.

Real-time applications such as instant messaging, data collection and analysis, document collaboration, and browser games are the most prevalent examples of the WebSockets protocol.

socket.io and websockets

Socket.IO is a JavaScript library that enhances WebSockets work. It consists of two sections: the server section (for Node.JS) and the client section (for web browsers). Both have event-driven architecture-based APIs that are similar. Socket.IO enables the use of capabilities such as transmitting data to a large number of sockets simultaneously (broadcasting) and storing the data.

The central concept of Socket.IO is the ability to transmit and receive any event containing any data. It might also be binary data or any other object.

socket.io in application - the chat ( based on examples from the official website of socket.io)

The easiest way to explain how Socket.IO operates is to illustrate it with an example. We can develop a simple WebSockets-based chat by writing only 22 lines of JavaScript code. With explanatory notes, the server and client components are provided below.

Node.JS is utilized by the server component, so it must be installed on the computer before proceeding. We will receive the node package manager (n) during the installation in order to install required packages.

Let's start with installing Express. Express is a Node.JS framework that facilitates the simplest work possible. Type this command to install it:

npm install express –save-dev

For our work we also need the Socket.IO library. Install its server part by typing the command:

npm install socket.io –save-dev

While installing dependencies with npm and the –save-dev argument, we add them to the package.json file.

// Use Express framework, which allows us to support HTTP protocol and Socket.IO
      var app = require('express')();
      var http = require('http').Server(app);
      var io = require('socket.io')(http);
      
      // Define the route and select the file - in this case it is index.html
      app.get('/', function(req, res){
          res.sendFile(__dirname + '/index.html');
      });
      
      // Listen 'connection' event, which is automatically send by the web client (no need to define it) 
      io.on('connection', function(socket){
          // Listen 'chat message' event, which is sent by the web client while sending request
          socket.on('chat message', function(msg) {
              // Emit event to all connected users. The second parameter should be the content of the message
              io.emit('chat message', msg);
            });
      });
      
      // Select the port to be listened by the server
      http.listen(3000, function() {
            console.log('Listening on *:3000');
      });

Since Express and Socket.IO have been deployed, the server portion of the application may now be developed. The JavaScript code that follows is annotated with explanations of its distinct components.

<!doctype html>
      <html>
          <head>
              <title>Socket.IO Chat</title>
              <style>
                    * { margin: 0; padding: 0; box-sizing: border-box; }
                    body { font: 13px Helvetica, Arial; }
                    form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
                    form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
                    form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
                  #messages { list-style-type: none; margin: 0; padding: 0; }
                  #messages li { padding: 5px 10px; }
                  #messages li:nth-child(odd) { background: #eee; }
              </style>
          </head>
          <body>
              <!-- The list of messages returned by Node.js server -->
              <ul id="messages"></ul>
      
              <!-- The form, which will be used to send messages -->
              <form action="">
                    <input id="message" autocomplete="off" />
                    <button>Send</button>
              </form>
      
          <!-- Add Socket.IO and jQuery -->
          <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
              <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
              <script>
                  // Create variable to which we ascribe Socket.IO mechanism
                    var socket = io();
      
                    // While submitting this form we also send 'chat message' event to the Node.JS server. The second parameter is a message entered in the file with 'message' id
                    $('form').submit(function(){
                      socket.emit('chat message', $('#message').val());
                      $('#message').val('');
                      return false;
                    });
      
                    // Listen 'chat message' event sent by Node.JS server. We will receive the content of this message as a parameter. Then assign it to the list of 'messages' id
                    socket.on('chat message', function(msg){
                      $('#messages').append($('<li>').text(msg));
                    });
              </script>
            </body>
      </html>

When both the server and client components are complete, we may launch the Node.JS server. Simply enter the command:

node server.js

Now navigate to this page and open it through two separate bookmarks. While inputting the message in one and sending it to the server, the text should appear in the other bookmark. Using just 22 lines of JavaScript code, this is how you can construct a real-time conversation. This is the wonder of WebSockets, and it's only the beginning — the possibilities are limitless.

Did you realize that two-way WebSockets may be used to connect the classic Snake game?

conclusion

WebSockets is one of HTML5's most innovative features. It resolves a number of issues that web application developers have previously encountered. WebSockets used with additional libraries such as Socket.IO offers a wide range of possibilities. Clearly, this is a big technological advancement.