WebSockets (WS) - the server-client relationship for receiving information from the server side without the need to pre-request the client part, receiving the so-called PUSH notification. The ideal JavaScript WebSocket interaction scheme looks like there is one stream in the server side that processes information, for example, listens to database changes or events triggered by other processes to send information to all clients simultaneously without using resources. The WebSocket client in JS and HTML5 using the WS interface is provided by most modern browsers: IE 10+, Chrome 16+, Firefox 11+, Safari 6+.
WebSockets Definition
Web sockets are defined as two-way communication between a server and a client. The key elements of JavaScript WebSocket are true concurrency and performance optimization, which leads to more responsive and rich web applications.
The protocol establishes full duplex communication from scratch. Web sockets are a step forward in providing desktop functionality in browsers. They demonstrate a new stage of evolution that has been expected for a long time in Internet technology client / server.
Key features of JavaScript WebSocket are as follows:
- The protocol is standardized, which means the possibility of using real-time communication between web servers and clients.
- Web sockets are becoming a cross-platform standard for real-time communication between client and server.
- The standard allows a new kind of application.
- With this technology, real-time businesses can speed things up.
The biggest advantage of JavaScript WebSocket is its 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, the proposed standard. RFC 6455 is supported by various browsers, such as Internet Explorer, Mozilla Firefox, Google Chrome.
Full duplex
Before moving on to the need for web sockets, you need to look at the existing methods that are used for duplex client Java WebSocket communication. They are as follows:
- voting;
- long survey;
- streaming
- postback and AJAX;
- HTML5
A survey can be defined as a method that performs periodic queries regardless of the data existing in the transmission. They are sent synchronously. The server response includes available data or some warnings.
A long survey, as the name implies, includes a similar survey technique. The client and server keep the connection active until some data is received or the timeout expires. If the connection is lost for any reason, the client Java WebSocket can start the procedure again and execute a sequential request. Long polling is nothing more than 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 transfer. The server keeps the connection open and active with the client until the necessary data is received. In this case, the connection is considered open indefinitely. Streaming includes HTTP headers that increase file size and delay. This can be considered as a major drawback.
This is a shortened form of asynchronous Javascript and XML. The XmlHttpRequest object allows you to run Javascript without reloading the entire web page. AJAX only sends and receives part of the web page. The main disadvantages of AJAX compared to JavaScript web sockets are:
- Send HTTP headers, which increases the overall size.
- The communication is half duplex.
- The web server consumes more resources.
HTML5 is a solid framework for developing and designing web applications. The main pillars are markup APIs, CSS3 and Javascript.
Functionality
WebSocket is a major update in the history of web communications. Before its existence, all communications between web clients and servers were based only on HTTP. Web Socket helps in the dynamic flow of connections that are persistent full duplex. Full duplex refers to communication from both ends with significant fast speed. This is called a game change due to its effective overcoming of all the shortcomings of existing protocols.
The importance of WS for developers and architects:
- An independent TCP-based protocol is designed to support any other protocol that traditionally only runs on top of a pure TCP connection.
- The transport layer, on top of which any other protocol can work.
The Websocket API supports the ability to define sub-protocols - protocol libraries that can interpret certain types of them. Examples of such protocols include XMPP, STOMP, and AMQP. Developers no longer need to think about the type of connection in terms of a request-response HTTP paradigm.
The only requirement on the browser side is to run a JavaScript library that can interpret the WS handshake, 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.
Web Socket Features:
- Connections via WebSocket are initiated via HTTP.
- HTTP servers typically interpret WS handshakes as an update request.
- Web sockets can complement 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 transferred in both directions between the client JavaScript WebSocket client and the server.
JavaScript implementation of the client
The source code for the JavaScript file named wsclient.js is included in the 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, for example, in Google Chrome, by choosing “File” -> “Open”.
A simple server can be easily implemented in Java. It simply returns the message received from the client in upper case:
- Open wsclient form.html in a web browser, and enter the necessary WebSocket connection parameters, and then click the "Connect" button. If the connection was successful, the button will be disconnected, and the “Disconnect” button will be turned on.
- Enter the message in the "Message text" field, and click the "Send" button. The server displays it in capital letters, and the JavaScript client displays it in the text area.
- The Google Chrome Developer Tools is a good tool for learning 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.
- Click on the "Title" tab to view the request and response values.
- 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 echo of the server in uppercase letters.
- The Timing tab shows how long the connection has been open.
- Consoles are used to look at the current instance of WS that is within the scope of the HTML page.
- They enter the variable name WebSocket JavaScript, WS and the console prints a JSON representation of the object.
- ReadyState. The property of the object displays the status of the connection. A value of 1 means that it is open, and ready to receive and send messages. It can be used to verify a WS connection before attempting to transfer data. If the connection is closed, the logic of its automatic reconnection can be implemented.
- Wireshark is a very comprehensive and useful tool for monitoring network traffic. It can be downloaded free of charge from the official website. After installation, launch it and select a network interface to capture traffic.
- To view only WS traffic, enter websocket in the filter field. Click on a frame to view the contents, including the actual message payload. Scroll down to the Line-based text data node and expand it.
- Right-click on 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
Spring-boot-starter-websocket - provides useful defaults for WS. First of all, configure the STOMP message broker. In it, WebSocketConfig.Java defines the STOMP endpoint of the message broker and the endpoint of the websocket application. @ Configuration is the Spring configuration class.
EnableWebSocketMessageBroker - enables message processing supported by the broker. It uses STOMP as a message broker.
The ConfigureMessageBroker () method allows a simple memory-based intermediary to send messages to the client at the recipients with the prefixes “/ topic” and “/ queue”. It also denotes the “/ app” prefix for those associated with annulled @Message Mapping methods in the controller class. This prefix will be used to identify all message displays. For example, “/ app / message” is the endpoint for which the WebSocket Controller.processMessage From Client () method is mapped.
Likewise, RegisterStompEndpoints () enables STOMP support and registers stomp endpoints in “/ greetings”. In this case, all JavaScript web socket messages will be routed through STOMP, which also adds an additional layer of security to the endpoint of the web socket. When creating a WS connection from javascript, only this specific Stomp endpoint is used.
In the configuration below, to enable support for SockJs to provide an optional reverse action, you need to make the following changes: registry.addEndpoint ("/ greeting") .withSockJS ().
The advantage of using sockJS here is that whenever a web socket connection is disconnected or cannot be established, then it will be downgraded to HTTP, and the connection between the client and server can still continue.
Error processing
As soon as a connection is established between the client and server, the Open event is fired from the WS instance. Errors that occur during communication are generated. This is determined using the OnError event. The occurrence of an error is always accompanied by a disconnection.
OnError - an event is raised when something goes wrong between communications. The event error is followed by termination of the connection. It is recommended that you always inform the user of unexpected errors, and try to reconnect the connection.
When it comes to error handling, you need to consider both internal and external parameters:
- Internal parameters include errors that can be generated due to errors in the code or unexpected user behavior.
- External errors have nothing to do with the application; rather, they are associated with parameters that cannot be controlled. The most important of these is network connectivity.
- Any interactive bi-directional web application requires an active internet connection.
Checking network availability
In modern desktop and mobile applications, a common task is to check network availability. The most common way for WebSocket php JavaScript is to make an HTTP request to a website that needs to be activated, for example google.com. If the request succeeds, the desktop or mobile device reports that an active connection exists. Similarly, HTML has an XMLHttpRequest for determining network availability.
HTML5 made this process even easier, and introduced a way to check if the browser can accept web responses. This is achieved using the object navigator.
Offline mode means that 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 data to the server and print the received response: import websocket.
OnOpen, OnClose, and OnMessage Events
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 the implementation of communication between the server and the WebSocket client, highlighting the triggered events and actions.
The WebSocket server works similarly to clients. He responds to events and, if necessary, performs actions. Regardless of the programming language used, each WebSocket server performs certain procedures. It is initialized to a web socket address, processes OnOpen, OnClose, and OnMessage events, and also sends messages to clients. There are four main Websocket API events:
- open;
- message;
- closed;
- error.
Each of the events is processed through the implementation of 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 the server: var server = new WebSocketServer ("ws: // localhost: 8181").
Any valid URL can be used with a port specification that has not been used before. It is very useful to keep track of connected clients, as it accumulates and stores various data or sends different messages to each of them.
Fleck represents inbound connections (clients) with the IwebSocketConnection interface. Whenever someone connects or disconnects from a service, you can create or update an empty list: var clients = new List ().
After that, call the Start method, and wait for the clients to connect. After starting, the server can accept incoming connections. In Fleck, the Start method needs a parameter that indicates the socket that raised the events: server.Start (socket) => {});
In order to implement the WebSocket server in C #, you need to use an external library. To get the same result in Java, you take advantage of the technology included in the standard library using the javax.websocket package, starting with 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 creating a new web application and will definitely use GlassFish as a server (version 4.0). If the user prefers to use Eclipse, he will have to choose Tomcat 8. Thus, they define a package that can be called MyServer and create a WebSocket Server class inside it. The code for implementing the server is readable, and its behavior is easy to understand.
Web Socket Benefits
WS solves several problems with REST or HTTP. HTTP is a unidirectional protocol in which a client always initiates a request. The server processes and returns the response, and then the client uses it. Websocket is a bidirectional protocol in which there are no predefined message templates such as request / response. Either the client or the server can send a message to the other side.
HTTP allows the request message to go 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. Typically, a new TCP connection is initiated for an HTTP request and terminates after receiving a response. You must establish a new TCP connection for another HTTP request / response.
For WS, the HTTP connection is updated using the standard update mechanism. The client and server communicate over the same TCP connection within the life cycle of the WS connection.
Websocket is a low level protocol. Everything, including a simple request / response template, ways to create, update, delete the necessary resources and status codes. All of them are carefully defined for HTTP.
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 of this must be defined on top of WebSocket and the Java database.