Sometimes, in a web application, it's necessary to have a constant exchange of data between the browser and the server. Imagine that we are developing an online chat. We want to display an up-to-date list of messages. Constantly sending an HTTP request to the server, which will update data on sent messages, is inconvenient and creates an additional load on the system (after all, we want the user to know about new messages immediately). For this purpose, there exists the WebSocket protocol.
WebSocket allows duplex communication between a browser and a server over a continuous connection. Duplex means that data on it can be transferred in both directions at any time without breaking the connection.
Opening WebSocket connection
To open a connection, we need to create an object using the built-in object, constructor WebSocket, and pass the URL address as an argument.
const socket = new WebSocket('wss://address/endpoint');
The WebSocket URL always starts with either ws or wss: ws is an unencrypted connection, while wss is encrypted. Like HTTP, URL starts with either http or https.
When we create an object with new WebSocket(), the browser starts to establish a connection with the server.
First, the browser sends an HTTP protocol to the server verifying that the server supports a WebSocket connection (also known as a handshake). After an affirmative response from the server, the parties begin to exchange data not via the HTTP protocol, but via the WebSocket protocol.
When a connection is opened, it handles the .onopen() event.
socket.onopen = function(event) {
console.log('Connection established!');
}readyState property
In order to get the state of the WebSocket connection, we can use the additional readyState property. It has the following values:
- 0 - "CONNECTING" means the connection is not yet established
- 1 - "OPEN" is for data exchange
- 2 - "CLOSING" means the connection is currently being closed
- 3 - "CLOSED" means the connection is already closed.
Data transfer via WebSocket
There is a .send() method for sending data to the server. Usually, this method accepts body as a string.
const body = {id: 66, text: 'Hello world!'};
socket.send(JSON.stringify(body));
When the client receives data, it fires the .onmessage event. This event has a data field, which contains the data transmitted by the server as a string.
socket.onmessage = function(event) {
console.log('Data received!');
console.log(event.data);
}
You can handle errors during operation using the .onerror event.
socket.onerror = function(error) {
console.log('An error has occurred!');
}Closing connection
In order to close the connection, we need to send a request to the server, and the server, in turn, must send a response to confirm the closure. You can also subscribe to this event using .onclose.
socket.onclose = function(event) {
console.log('Connection interrupted!');
}
To prevent unexpected disconnections, the server periodically sends a response to the client asking to check the connection. If the client does not respond after some time, the server closes the connection.
WebSocket example
You should familiarize yourself with the example below where we have collected all the events and basic methods.
This code snippet only serves to bring together all of the WebSocket API methods and events. This code will not give any results if we run it because of the dummy URL.
// Using the WebSocket constructor-object allows you to open a connection and use WebSocket methods
let socket = new WebSocket("wss://address/endpoint");
// Event that fires when a WebSocket connection is opened
socket.onopen = function(event) {
console.log('Connection established!')
};
// Event that fires when the WebSocket connection get new data
socket.onmessage = function(event) {
console.log('Data received!');
console.log(event.data);
};
// Event that fires when the WebSocket connection is closed
socket.onclose = function(event) {
console.log('Connection interrupted!');
};
// Event that fires when the WebSocket connection gets an error
socket.onerror = function(event) {
console.log('An error has occurred!');
};
// WebSocket method that allows you to send data to the server
socket.send('Hello world!');
// WebSocket method that allows you to close WebSocket connection
socket.close();Conclusion
Websocket is a data transfer protocol that allows a client and a server to exchange data through a single handshake indefinitely.
To create a WebSocket connection, you should use the built-in WebSocket object. Also, you can send data from the client to the server using the .send method and close the connection using the .close() method. The created object has four events that you can monitor: open, message, error, and close.