JavaScript WebSocket: description, principle of operation, application

Table of contents:

JavaScript WebSocket: description, principle of operation, application
JavaScript WebSocket: description, principle of operation, application
Anonim

WebSockets (WS) - the relationship between the server and the client to receive information from the server side without the need to first request the client side, receiving the so-called PUSH notification. The ideal JavaScript WebSocket communication pattern would be to have a single thread on the backend that processes information, such as listening for database changes or events triggered by other processes, to send information to all clients simultaneously without using resources. WebSocket client in JS and HTML5 using WS interface, provided by most modern browsers: IE 10+, Chrome 16+, Firefox 11+, Safari 6+.

Defining WebSockets

Definition of WebSockets
Definition of WebSockets

Web sockets are defined as a two-way communication between a server and a client. The key points of JavaScript WebSocket are true concurrency and performance optimization, resulting in more responsive and rich web applications.

The protocol establishes full duplex communication from scratch. Web sockets are a step forward in bringing desktop functionality to browsers. They show a new stagean evolution long anticipated in Internet client/server technology.

The main features of JavaScript WebSocket are as follows:

  1. The protocol is standardized, which means it is possible to organize communication between web servers and clients in real time using the help.
  2. Web sockets are emerging as a cross-platform standard for real-time communication between client and server.
  3. The standard allows for a new kind of application.
  4. Using this technology, real-time businesses can speed up operations.

The biggest advantage of JavaScript WebSocket is the two-way communication (full duplex) over a single TCP connection. HTTP has its own set of schemes such as http and https. The web socket protocol also has a similar scheme defined in its URL pattern. The latest WS protocol specification is defined as RFC 6455, a proposed standard. RFC 6455 is supported by various browsers such as Internet Explorer, Mozilla Firefox, Google Chrome.

Duplex communication

duplex communication
duplex communication

Before we get to the need for Web Sockets, we need to take a look at the existing methods that are used to duplex the Java WebSocket client. They are as follows:

  • vote;
  • long survey;
  • streaming;
  • postback and AJAX;
  • HTML5.

Polling can be defined as a method that performs periodic queries regardless of the data present in the transmission. They are sent synchronously. The server response includes available data or some warnings.

Long polling, as the name suggests, involves a similar polling technique. The client and server keep the connection active until some data is received or time out. If the connection is lost for some reason, the Java WebSocket client can start over and make the subsequent request. The long polling is nothing but a performance improvement over the polling process, but constant requests can slow down the process.

Streaming and AJAX options

This is considered the best option for real-time data transmission. The server keeps the connection open and active with the client until the required data is received. In this case, the connection is considered open indefinitely. Streaming includes HTTP headers that increase file size and latency. This can be seen as a major drawback.

This is a shorthand form of asynchronous Javascript and XML. The XmlHttpRequest object allows you to execute Javascript without reloading the entire web page. AJAX sends and receives only part of a web page. The main disadvantages of AJAX compared to JavaScript websockets are:

  1. Send HTTP headers, which increases the overall size.
  2. Communication is half duplex.
  3. The web server consumes more resources.

HTML5 is a solid framework for developing and designing web applications. The main pillars are API-markup interfaces, CSS3 and Javascript.

Functionality

Functionality
Functionality

WebSocket represents a major update in the history of web communications. Prior to its existence, all communications between web clients and servers were based solely on HTTP. Web Socket helps in the dynamic flow of connections that are constant full duplex. Full duplex refers to communication from both ends at a significant fast speed. It is called a game changer due to its effective overcoming of all the shortcomings of existing protocols.

Importance of WS for developers and architects:

  1. An independent protocol based on TCP, designed to support any other protocol that traditionally only runs on top of a pure TCP connection.
  2. A transport layer that any other protocol can run over.

Websocket API supports the ability to define subprotocols - protocol libraries that can interpret certain protocol types. Examples of such protocols include XMPP, STOMP, and AMQP. Developers no longer need to think about connection type in terms of the HTTP request-response paradigm.

The only requirement on the browser side is to run a JavaScript library that can interpret the WS handshake and establish and maintain a connection. On the server side, the industry standard is to use existing protocol libraries that run on top of TCP and use a gateway.

Functionalityweb sockets:

  1. WebSocket connections are initiated over
  2. HTTP servers usually interpret WS handshakes as a request to update.
  3. Web sockets can be an addition to the existing HTTP environment and can provide the necessary infrastructure to add web functionality. They rely on more advanced full-duplex protocols that allow data to be passed in both directions between the client JavaScript WebSocket client and the server.

Implementing the client in JavaScript

The JavaScript source code for a file named wsclient.js is included in an HTML5 page so that it can open a WebSocket connection. The script contains code to create a WS client using its interface.

A simple HTML5 page is used to create a form for connecting to a server endpoint and messaging. The HTML page uses the wsclient.js script to run the HTML file, open it in a browser such as Google Chrome by selecting "File" -> "Open".

A simple server can be easily implemented in Java. It simply returns the message received from the client in uppercase:

  1. Open wsclient form.html in a web browser, enter the required WebSocket connection parameters, and then click the "Connect" button. If the connection was successful, the button will be disabled and the Disconnect button will be enabled.
  2. Enter a message in the "Message text" field, and click the "Send" button. The server will display it in capital letters, and the JavaScript client will display it in textarea.
  3. Google Chrome's "developer tools" are a good tool for learning about WebSocket connections. In the Developer Tools window, go to the Network tab and select WS to view a list of all connections for the current page.
  4. Click on the "Header" tab to view the request and response values.
  5. The Frames tab lists all outgoing and incoming messages. The first message is what was sent from the client to the server, and the second message is the server's echo in capital letters.
  6. Timing tab shows how long the connection has been open.
  7. Console is used to look at the current WS instance that is within the scope of the HTML page.
  8. Enter a WebSocket JavaScript variable name, WS and the console will print the JSON representation of the object.
  9. ReadyState. The property of the object displays the state of the connection. A value of 1 means that it is open and ready to receive and send messages. It can be used to test the WS connection before attempting to transfer data. If the connection is closed, logic can be implemented to automatically reconnect it.
  10. Wireshark is a very comprehensive and useful tool for monitoring network traffic. It can be downloaded for free from the official website. After installation, launch it and select a network interface to capture traffic.
  11. To view only WS traffic, enter websocket in the filter field. Click on the frame to view the content, includingthe actual payload of the message. Scroll down to the Line-based text data of the node and expand it.
  12. Right click the compressed payload and select "Show Packet Bytes". In the dialog box, select "Compressed" from the "Decode" drop-down list to view the payload in plain text.

Configure Java WebSocket spring

Java WebSocket spring setup
Java WebSocket spring setup

Spring-boot-starter-websocket - Provides useful defaults for WS. First of all, configure the STOMP message broker. In it, WebSocketConfig. Java defines a message broker STOMP endpoint and a websocket application [email protected] is a Spring configuration class.

EnableWebSocketMessageBroker - Enables message processing supported by the broker. This uses STOMP as a message broker.

The ConfigureMessageBroker() method allows a simple memory-based broker to relay messages to the client at destinations prefixed with "/topic" and "/queue". It also denotes the "/app" prefix for those associated with the invalidated @Message Mapping methods in the controller class. This prefix will be used to define all message mappings. For example, "/app/message" is the endpoint mapped to the WebSocket Controller.processMessage From Client() method.

Similarly, RegisterStompEndpoints() enables STOMP support and registers stomp endpoints in "/hello". In this case, all JavaScript web socket messages will be routed through STOMP,which also adds an extra layer of security to the websocket endpoint. When creating a WS connection from javascript, use only this specific Stomp endpoint.

In the configuration below, to enable SockJs support to provide an optional callback, the following changes need to be made: registry.addEndpoint("/hello").withSockJS().

The advantage of using sockJS here is that whenever a websocket connection is disabled or cannot be established, then it will be downgraded to HTTP and communication between client and server can still continue.

Java WebSocket spring setup
Java WebSocket spring setup

Error Handling

As soon as a connection is established between the client and the server, the Open event is fired from the WS instance. Errors that take place during communication are generated. This is determined using the OnError event. The occurrence of an error is always accompanied by a disconnection.

OnError - event is fired when something goes wrong between communications. An event error is followed by a connection termination. It is recommended to always inform the user about unexpected errors and try to reconnect the connection.

When it comes to error handling, both internal and external parameters need to be considered:

  1. Internal parameters include errors that may be generated due to errors in code or unexpected user behavior.
  2. External errors have nothing to do with the application,rather, they are related to parameters that cannot be controlled. The most important of these is network connectivity.
  3. Any interactive bidirectional web application requires an active internet connection.

Checking network availability

In today's desktop and mobile applications, a common task is to check for network availability. The most common way for WebSocket php JavaScript is to make an HTTP request to a website that needs to be activated, like google.com. If the request succeeds, the desktop or mobile device reports that there is an active connection. Similarly, HTML has an XMLHttpRequest to determine if the network is available.

HTML5 made this process even easier, and introduced a way to check if a browser can accept web responses. This is achieved using the object navigator.

Checking network availability
Checking network availability

Offline mode means either the device is not connected or the user has selected offline mode on the browser toolbar.

Testing Java WebSocket uses a simple WS-client. Once the connection is established, send the data to the server and print the received response: import websocket.

For testing Java WebSocket
For testing Java WebSocket

Events OnOpen, OnClose and OnMessage

WebSocket server is a simple program that can handle WS events and actions. It usually provides methods similar to the client API. At the same time, most programming languages provide an implementation of communicationbetween the WebSocket server and client, highlighting triggered events and actions.

WebSocket server works similarly to clients. It reacts to events and, if necessary, performs actions. Regardless of the programming language used, each WebSocket server performs certain procedures. It initializes with a web socket address, handles the OnOpen, OnClose, and OnMessage events, and sends messages to clients. There are four main Websocket API events:

  • open;
  • message;
  • closed;
  • error.

Each of the events is handled by implementing functions such as OnOpen, OnMessage, OnClose and OnError respectively. This can also be implemented using the addEventListener. method

Web socket instance in Java

Each WS server requires a valid host and port. An example of creating a Websocket instance on a server: var server=new WebSocketServer("ws://localhost:8181").

Any valid URL can be used with a port specification that has not been previously used. It is very useful to keep a record of connected clients as it accumulates and saves different data or sends different messages to each of them.

Fleck represents incoming connections (clients) with the IwebSocketConnection interface. Whenever someone connects to or disconnects from the service, an empty list can be created or updated: var clients=new List ().

After that, the Start method is called, and the clients are waiting for connection. After starting the serveraccept incoming connections. In Fleck, the Start method needs a parameter that specifies the socket that fired the events: server. Start(socket)=>{});

In order to implement a WebSocket server in C, you need to use an external library. To achieve the same result in Java, it takes advantage of technology included in the standard library using the javax.websocket package since Java EE 7.

Create a Java WebSocket client project based on Java EE 7 using one of the free online IDEs such as Eclipse and NetBeans. NetBeans is building a new web application and making sure to use GlassFish as the server (version 4.0). If the user prefers to use Eclipse, they will have to choose Tomcat 8. So they define a package that can be called MyServer, and within that create a WebSocket Server class. The code for the server implementation is quite readable and its behavior is easy to understand.

Web Sockets Instance in Java
Web Sockets Instance in Java

Web socket benefits

WS solves several problems with REST or HTTP. HTTP is a unidirectional protocol in which the client always initiates a request. The server processes and returns the response, and then the client uses it. Websocket is a bi-directional protocol with no predefined message patterns like request/response. Either the client or the server can send a message to the other side.

HTTP allows the request message to travel from the client to the server, and then it sends a response. At a certain point in time, the client communicates with the server, or vice versa. HowTypically, a new TCP connection is initiated for an HTTP request and terminated after receiving a response. Need to establish a new TCP connection for another HTTP request/response.

For WS, the HTTP connection is refreshed using the standard refresh mechanism. Client and server communicate over the same TCP connection within the WS connection lifecycle.

Websocket is a low level protocol. Everything, including a simple request/response pattern, how to create, update, delete required resources, and status codes. They are all carefully defined for

WS is a stateful protocol while HTTP is a stateless protocol.

WS connections can scale vertically on a single server, while HTTP can scale horizontally. There are several proprietary solutions for horizontal scaling, but they are not based on standards.

HTTP comes with many other benefits such as caching, routing and multiplexing. All this should be defined on top of WebSocket and Java database.

Popular topic

Editor's choice

  • Restore Skype account: step by step instructions, return access to your account
    Restore Skype account: step by step instructions, return access to your account

    Don't know how to recover your Skype account? Or do you want to know your friend's Skype password? The article discusses several ways to restore the user's page, as well as recommendations for storing and selecting pin codes

  • Why can't I follow on Instagram? All possible reasons
    Why can't I follow on Instagram? All possible reasons

    We subscribe to people with a specific goal - to find friends, like-minded people of interest, to learn something new for ourselves. And sometimes it is very strange to see that the Instagram system does not allow you to "follow" the profile you are interested in. This error occurs quite often, no one is immune from this trouble. Let's analyze the main reasons why Instagram does not allow you to subscribe to people

  • How to find out who "liked" a person on Instagram. Proven Methods
    How to find out who "liked" a person on Instagram. Proven Methods

    Everyone who is trying to start the path of a blogger or has already achieved some success in this field, hopes that the content that he shares with readers will not be left without attention. The main indicator of page popularity is “likes”. “Thumbs up” is also put when they want to attract the attention of potential subscribers

  • How to restore a channel on YouTube: detailed instructions, simple and effective tips
    How to restore a channel on YouTube: detailed instructions, simple and effective tips

    This article describes how to restore a channel on YouTube after deleting it. To understand this task, it will be useful to familiarize yourself with some terminology. There is a difference between deleting and blocking a YouTube account

  • How to remove a contact from "Vatsap" and how to block an unwanted interlocutor
    How to remove a contact from "Vatsap" and how to block an unwanted interlocutor

    WhatsApp is a popular messenger. It has many features that users are not even aware of. One of these is the ability to block contacts. It helps to get rid of annoying interlocutors. And how to remove a contact from WhatsApp and how to block it? You can perform these actions in different ways