Step 1: Create folder structure.
In your code editor, create a public folder with index.html, index.css and script.js files. In the root directory, create a server.js file to set up an Express server. Also, create a JSON file by typing the following command in your terminal.
Step 2: Install dependencies
In your VS Code terminal, install the following dependencies. Then install the following:
npm i express
npm i socket.io
npm i nodemon
Step 3: Set up the Express server in the server.js file
This is an express server running on port 3002.
First, we import the Express framework and create an instance of the Express application using the app variable.
The app will be used to define routes (URLs) to send, respond and handle requests.
app.listen(3002,()=>{...}): Starts the server and tells it to listen on port 3002.
### Step 4: Set up nodemon to run the server**
In package.json file, go to scripts section and create a new script called “dev”. Set its value to nodemon followed by the name of the file where you will create your server e.g., “server”.
This allows you run the server using npm run dev. Nodemon reloads the server automatically whenever you make changes so you do not have to do it manually.
Step 5: Start node server using “npm run dev”
If you see the server running on port 3002 in your terminal with the console message, the server has started running.
Step 5: Test the local host
Create a GET route (app.get) for the root URL (http://localhost:3002/) so that when you visit the URL, you get a response from the server.
Now that you’ve tested to see that the server is running as it should, integrate socket.io into your server.js file. Let’s go through what the above code is doing.
We have installed several modules:
express: Used for building a web server.
http: Node module to create a server.
path: File path resolution.
socket.io: Enables real-time bi-directional communication between client and server.
app: Instance of express.
server: Node HTTP server that uses express app.
io: An instance of socket.io attached to the server.
Express.static: Serves static files from the public folder. Note: The HTML, CSS, and JavaScript files are located in the public folder.
io.on("connection", (socket)=>{ console.log ("user connected", socket.id): listens for a new client connection and gives each client a unique id. It runs when a user connects to the server.
socket.on("chat message", (msg)=>{....}): Listens for chat message events from a client, logs the message, and emits (sends an event with data) to all connected clients, including the sender.
Step 7: Create an HTML file that connects to the server and allows you to send and receive messages.
Step 8: Style HTML elements
Message Style: The message is what we send from the input. Styling remove bullet points, sets a fixed height, enables scrolling, and adds space after each message list for readability.
Input Style: Styles the input field to grow using flex, adds padding for spacing, and border radius.
Button Style: Styles the button with a blue background, pointer cursor, white text, and a border-radius.
Step 9: Connect to the Socket.io server, send and display messages
Code breakdown:
Select elements by their ID from the HTML document using querySelector
form.addEventListener("submit" (e) =>{...}): Listens for form submission.
e.preventDefault(): Prevents default submission behaviour, which causes the page to reload.
username = usernameInput.value.trim() || "Anonymous": Checks if the username is empty; if yes, defaults to "Anonymous".
if(input.value.trim() checks if the input field contains any value. trim() removes whitespace from the string
if there's a value or message, const messageToSend= ${username}: ${input.value} combines the username and message into a string.
socket.emit("chat message", messageToSend): sends the message to the server with the "chat message" event, which the server sends to all connected clients
Input.value = " ": clears the input field
socket.on("chat message”, (msg) =>{..}): Listens for incoming "chat message" events from the server. The msg represents data sent by the server when it emits the "chat message" event.
A new list item
is created and appended to the