![](/style/images/good.png)
![](/style/images/bad.png)
Medhat Elmasry: Build a socket.io chat web app with node.js
source link: https://blog.medhat.ca/2022/03/build-socketio-chat-web-app-with-nodejs.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Socket.IO is a JavaScript library for real-time web applications. It enables real-time, bi-directional communication between web clients and servers.
This article addresses the very basic building blocks to creating a socket.io application in Node.js.
Source code: https://github.com/medhatelmasry/socket-chat.git
Pre-requisites
- The latest versions of Node.js & npm are installed on your computer
- You have some basic knowledge of Node.js and Express
Getting started
mkdir socket-chatcd socket-chat
npm init -y
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server, { cors: { origin: "*" } });
app.set("view engine", "ejs");
app.get("/", (req, res) => {
res.render("index", {title: "Socket.io chat example"});
});
const port = process.env.PORT || 3030;
server.listen(port, () => {
console.log(`Server started and listening on port ${port}`);
});
// emit & receive messages
io.on('connection', (socket) => {
console.log(`Someone connected with socket id: ${socket.id}`);
});
What does the above code do?
- we initialize express, server, and io
- EJS is declared as our view engine
- the / route points to a view page named index. This will be created later.
- the server will be started on port 3030
- whenever someone connects, the unique socket id is displayed in the server console
Edit file package.json and add the following to the "scripts" section:
<!DOCTYPE html><html lang="en"><head><title><%- title %></title><script src="https://cdn.socket.io/socket.io-3.0.1.min.js"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"/></head><body><div class="container"><h3><%- title %></h3>
</div></body></html>
Also in views/index.ejs, add the following JavaScript code below the closing </div> tag:
<script>const socket = io('http://localhost:3030');socket.on("connection", () => {});
</script>
<input type="text" id="msg" /><button onclick="sendMessage()" class="btn btn-success btn-sm">Send Message</button><hr /><ul id="msgList" class="list-group"></ul>
socket.on('chat', (data) => {console.log(data);// broadcast the same message to all except the sendersocket.broadcast.emit('chat', data);
const sendMessage = () => {const msgInput = document.querySelector("#msg");socket.emit("chat", msgInput.value);document.querySelector("#msg").value = "";
socket.on("chat", (data) => {const msg = data.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");var li = document.createElement("li");li.classList.add("list-group-item", "list-group-item-warning");li.textContent = msg;document.querySelector("#msgList").appendChild(li);
What does the above code do?
- data is sanitized such that & is replaced by & and < is replaced by < and > is replaced by >
- an li element is created and given bootstrap styling
- data is assigned as content to the li element
- finally, the li item is appended to the unordered list with id msgList
Testing our chat app
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK