WebSockets are a technology for creating real-time, bi-directional communication channels over a single TCP connection. They help build applications that require low-latency, high-frequency communication, such as chat applications, online gaming, and collaborative software.
Prerequisites
- Basic understanding of JavaScript
- Basic understanding of Node.js and React
- Basic understanding of web development concepts, such as HTTP and HTML
- Node.js and npm installed on your machine
- React developer tools installed in your browser (optional, but helpful for debugging)
Setting up the Server
mkdir real-time-chat-appcd real-time-chat-app
npm init -y
npm install socket.io
const http = require('http');const io = require('socket.io');
const server = http.createServer((req, res) => {
res.end('Server is running!');});const port = 3000;server.listen(port, () => {console.log(`Server is listening on port ${port}`);});
const ioServer = io.listen(server);
Now that we have set up the server, let’s move on to setting up the client-side code.
Setting up the Client
npm start
import React, { useState, useEffect } from 'react';import io from 'socket.io-client';
- messages: an array of messages that have been received from the server
- sendMessage: a function that can be called to send a message to the server
- error: an error object that will be set if there is an error in the WebSocket connection
function useWebSocket() {const [messages, setMessages] = useState([]);const [error, setError] = useState(null);useEffect(() => {const socket = io('http://localhost:3000');socket.on('connect', () => {console.log('Connected to server!');});socket.on('disconnect', () => {console.log('Disconnected from server');});socket.on('error', (error) => {setError(error);});socket.on('message', (message) => {setMessages((prevMessages) => [...prevMessages, message]);});return () => {socket.disconnect();};}, []);const sendMessage = (message) => {if (socket.connected) {socket.send(message);}};return { messages, sendMessage, error };}
function App() {const { messages, sendMessage, error } = useWebSocket();if (error) {return <div>Error: {error.message}</div>;}return (<div><ul>{messages.map((message) => (<li>{message}</li>))}</ul><form onSubmit={(event) => {event.preventDefault();const messageInput = event.target.elements.message;sendMessage(messageInput.value);messageInput.value = '';}}><input name="message" /><button type="submit">Send</button>function App() {const { messages, sendMessage, error } = useWebSocket();if (error) {return <div>Error: {error.message}</div>;}return (<div><ul>{messages.map((message) => (<li>{message}</li>))}</ul><form onSubmit={(event) => {event.preventDefault();const messageInput = event.target.elements.message;sendMessage(messageInput.value);messageInput.value = '';}}><input name="message" /><button type="submit">Send</button></form></div>);}export default App;
Now let’s move on to handling the messages on the server side.
Handling Messages on the Server
ioServer.on('connection', (socket) => {console.log('New client connected');socket.on('message', (message) => {console.log(`Received message from client: ${message}`);ioServer.emit('message', message);});socket.on('disconnect', () => {console.log('Client disconnected');});});
Now, if you start the server by running node server.js and navigate to http://localhost:3000 in the browser, you should be able to send messages and see them displayed in real-time.
Conclusion
You can extend this application in many ways, such as adding user authentication, storing messages in a database, and implementing more advanced features like message editing and deletion. I hope this tutorial has provided a good foundation for you to build upon.



We’re a gaggle of volunteers and opening a brand new scheme
in our community. Your web site provided us with helpful information to work
on. You have performed a formidable activity and our whole group shall be grateful to you.