Websockets are a powerful technology that allows for real-time, bidirectional communication between clients (typically web browsers) and servers. In this example, we’ll explore how to implement Websockets in JavaScript to enable real-time communication.
Setting up a Websocket connection
To establish a Websocket connection, we first need to create an instance of the WebSocket
object. We pass the URL of the server endpoint as an argument to the constructor. For example:
const socket = new WebSocket("wss://example.com/socket");
In this example, we’re connecting to a WebSocket server hosted at wss://example.com/socket
.
Handling WebSocket events
Next, we need to handle various events that can occur during the lifecycle of a WebSocket connection. The WebSocket
object provides a set of event handlers that we can attach to.
socket.onopen = function() {
console.log("WebSocket connection established.");
};
socket.onmessage = function(event) {
const message = event.data;
console.log("Received message:", message);
};
socket.onclose = function() {
console.log("WebSocket connection closed.");
};
socket.onerror = function(error) {
console.error("WebSocket error:", error);
};
In the above code, we’re logging messages to the console whenever the WebSocket connection is established (onopen
), when a message is received from the server (onmessage
), when the connection is closed (onclose
), and when an error occurs (onerror
).
Sending messages over Websockets
To send a message to the server, we can use the send
method of the WebSocket
object. The data to be sent can be a string, an ArrayBuffer, a Blob, or a TypedArray. For example:
socket.send("Hello, server!");
In this example, we’re sending the string “Hello, server!” to the WebSocket server.
Closing the Websocket connection
To close the WebSocket connection, we can call the close
method on the WebSocket
object. By default, the server is also notified about the closure.
socket.close();
Conclusion
Websockets are a powerful tool for enabling real-time communication between clients and servers. In this example, we learned how to set up a Websocket connection, handle WebSocket events, send messages, and close the connection. By leveraging Websockets, you can build dynamic, real-time applications that provide a seamless user experience.
Now that you have a basic understanding of how to use Websockets in JavaScript, you can explore various libraries and frameworks that provide higher-level abstractions for Websocket communication.