GraphQL / Subscriptions in GraphQL
Setting Up WebSockets for Real-Time Updates
This tutorial will teach you how to use WebSockets for real-time updates in your applications. You'll get a clear understanding of how WebSockets work and how to implement them.
Section overview
5 resourcesExplains how to set up real-time communication using GraphQL subscriptions.
Introduction
In this tutorial, we are going to learn about WebSockets, a powerful tool that enables real-time, two-way communication between a client and a server over a single, long-lived connection. This technology is crucial for applications that require instant updates, such as chat apps, live sports updates, or stock market apps.
You will learn:
- What WebSockets are and how they work.
- How to set up a WebSocket server.
- How to connect a client to the WebSocket server and exchange data.
Prerequisites:
- Basic knowledge of JavaScript and Node.js.
- Node.js and NPM installed on your machine.
- A text editor, such as Visual Studio Code.
- A web browser.
Step-by-Step Guide
A. Understanding WebSockets
WebSockets provide a persistent connection between a client and a server that both parties can use to start sending data at any time. This is different from the traditional HTTP protocol where the client has to initiate the connection.
B. Setting up a WebSocket Server
We'll use the ws library to set up a WebSocket server in Node.js. First, navigate to your project directory and run:
npm install ws
Next, create a new JavaScript file, let's call it server.js, and add the following code:
// Import the WebSocket library
const WebSocket = require('ws');
// Create a WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });
// When a connection is established
wss.on('connection', (ws) => {
console.log('New client connected');
// When a message is received from the client
ws.on('message', (message) => {
console.log('Received: ' + message);
});
// Send a message to the client
ws.send('Hello from server');
});
C. Connecting a Client to the Server
Let's create a new client.html file and add the following code:
<!DOCTYPE html>
<html>
<body>
<script>
// Connect to the WebSocket server
let socket = new WebSocket("ws://localhost:8080");
// When the connection is open, send some data to the server
socket.onopen = function(e) {
alert("[open] Connection established");
socket.send("Hello from client");
};
// When a message is received from the server
socket.onmessage = function(event) {
alert(`[message] Data received from server: ${event.data}`);
};
</script>
</body>
</html>
Code Examples
In both the server and client code, we've used the ws library and the native WebSocket API respectively to open a connection, send and receive messages.
A. Server Code Explanation
Here's a breakdown of the server code:
const WebSocket = require('ws');: Import the WebSocket library.const wss = new WebSocket.Server({ port: 8080 });: Create a WebSocket server on port 8080.wss.on('connection', (ws) => {...});: Listen for any incoming connections. When a client connects, the callback function is called with the WebSocket (ws) representing the connection.ws.on('message', (message) => {...});: Inside the connection callback, we set up a listener for any messages from the client.ws.send('Hello from server');: Also inside the connection callback, we send a message to the client.
B. Client Code Explanation
Here's a breakdown of the client code:
let socket = new WebSocket("ws://localhost:8080");: Connect to the WebSocket server.socket.onopen = function(e) {...};: When the connection is open, send a message to the server.socket.onmessage = function(event) {...};: Listen for any messages from the server.
Summary
In this tutorial, you've learned the basics of working with WebSockets for real-time communication. You've set up a simple WebSocket server in Node.js and connected a client to it. You've also learned how to send and receive messages.
To learn more about WebSockets, check out the WebSocket API documentation and the ws library documentation.
Practice Exercises
- Modify the client to send a message every 5 seconds.
- Modify the server to broadcast a message to all connected clients whenever a new client connects.
- Create a chat app where multiple clients can connect and send messages to each other.
Remember, the best way to learn is by doing. Good luck and happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article