An Introduction to WebSockets in JavaScript
WebSockets are a powerful technology that enable real-time, two-way communication between a client and server over a single TCP (Transmission Control Protocol) connection. In other words, WebSockets provide a channel for continuous communication without the need for constant HTTP requests and responses.
WebSockets were introduced in HTML5, and since then they have been gaining popularity for developing web applications, multiplayer games, chat applications, and other real-time applications. In this article, we’ll explore the basics of WebSockets in JavaScript.
WebSocket API
The WebSocket API is a JavaScript interface that allows us to open a WebSocket connection and communicate with a remote host. The API consists of:
1. The WebSocket object – It is used to open and manage a WebSocket connection. We create a new WebSocket object and pass the URL of the server endpoint as an argument.
2. Events – WebSocket provides a set of events that we can use to listen to the state of the WebSocket connection such as “open”, “message”, “close”, and “error”.
Opening a WebSocket Connection
To open a WebSocket connection, we create a new WebSocket object and pass the URL of the server endpoint. For example, the following code creates a new WebSocket connection to the server endpoint at “wss://example.com/ws”:
“`
const socket = new WebSocket(‘wss://example.com/ws’);
“`
Listening to WebSocket Events
WebSocket provides a set of events that we can use to listen to the state of the connection. Here’s a list of some of the commonly used events:
1. “open” – This event fires when the WebSocket connection is established.
2. “message” – This event fires when a message is received from the server.
3. “close” – This event fires when the WebSocket connection is closed.
4. “error” – This event fires when an error occurs with the WebSocket connection.
Here’s an example of how to listen to WebSocket events:
“`
// Listening to “open” event
socket.addEventListener(‘open’, (event) => {
console.log(‘WebSocket connection established’);
});
// Listening to “message” event
socket.addEventListener(‘message’, (event) => {
console.log(`Received message from server: ${event.data}`);
});
// Listening to “close” event
socket.addEventListener(‘close’, (event) => {
console.log(‘WebSocket connection closed’);
});
// Listening to “error” event
socket.addEventListener(‘error’, (error) => {
console.error(‘WebSocket connection error’, error);
});
“`
Sending Data over WebSocket
Sending data over WebSocket is as simple as calling the “send” method on the WebSocket object. The “send” method takes a single argument that can be a String, ArrayBuffer, or Blob. Here’s an example of how to send a string message:
“`
socket.send(‘Hello, World!’);
“`
Closing WebSocket Connection
To close the WebSocket connection, we can call the “close” method on the WebSocket object. The “close” method takes two optional arguments: a numeric code specifying the reason for closing the connection, and a string reason for closing the connection. Here’s an example of how to close the WebSocket connection:
“`
socket.close();
“`
Conclusion
WebSockets provide a powerful mechanism for real-time communication between a client and server without the need for constant HTTP requests and responses. With the WebSocket API in JavaScript, it’s easy to open a WebSocket connection, send and receive data, and close the connection. WebSockets are suitable for developing applications that require live data exchange, such as real-time multiplayer games, chat applications, and financial tickers.