如何在Node.js中使用Demo-Chat App配置Socket.IO?
Socket.io是一個流行的JavaScript庫,允許我們在伺服器和客戶端之間進行通訊。我們可以在客戶端和伺服器端建立一個socket.io例項,並監聽或發出雙方的事件。此外,我們可以監聽伺服器在多個Web客戶端上發出的事件。
在即時應用中,我們可以使用socket.io庫建立需要雙向通訊的聊天應用程式和線上遊戲。例如,如果您在玩象棋或盧多遊戲時觀察到,它允許我們與對手交談。
在本教程中,我們將學習如何在Node.js中使用socket.io配置一個演示聊天應用程式。
使用者應按照以下步驟建立聊天應用程式。
步驟1 − 首先,我們需要建立一個Node專案。使用者應在專案目錄中執行以下命令。
npm init -y
步驟2 − 之後,我們需要透過在專案目錄中執行以下命令來安裝Node專案中的依賴項。
npm i express socket.io
步驟3 − 現在,執行以下命令在專案中建立空檔案。
touch app.js index.html
使用者現在可以觀察到app.js和index.html檔案已在專案目錄中建立。
步驟4 − 接下來,我們將為Node應用程式建立一個伺服器。
步驟4.1 − 首先,匯入所需的依賴項,並初始化應用程式。
const app = express(); const { Server } = require("socket.io"); const server = http.createServer(app); const io = new Server(server);
步驟4.2 − 配置路由併發送index.html檔案。
app.get("/", (req, res) => { res.sendFile(__dirname + "/index.html"); });
步驟4.3 − 建立與客戶端的連線。
io.on("connection", (socket) => { });
步驟4.4 − 每當伺服器端接收到“send name”事件時,它會再次從伺服器發出該事件。因此,所有連線的客戶端都可以接收事件和訊息。
socket.on("send name", (username) => { io.emit("send name", username); });
步驟4.5 − 編寫相同的程式碼來監聽和發出“send message”事件。
步驟4.6 − 編寫執行Node伺服器的程式碼。
server.listen(port, () => { console.log(`Server is listening at the port: ${port}`); });
步驟5 − 我們已成功設定了Node伺服器。現在,我們需要設定客戶端。
步驟5.1 − 在index.html檔案中,建立輸入以獲取名稱和訊息輸入。另外,建立一個“傳送”按鈕。此外,設定HTML元素的樣式以使其更具吸引力。
步驟5.2 − 在JavaScript中,初始化socket連線。
let socket = io();
步驟5.3 − 在按鈕上新增點選事件。每當使用者點選按鈕時,訪問名稱和訊息值,併發出“send name”和“send message”事件。
socket.emit('send name', myName.value); socket.emit('send message', myMessage.value);
步驟5.4 − 每當我們在客戶端監聽“send message”或“send name”事件時,獲取訊息並將其附加到網頁。
這裡,我們提供了完整的程式碼示例。
示例
檔名 – Index.html
使用者應複製以下程式碼並將其貼上到專案的index.html檔案中。在此檔案中,我們獲取輸入值並使用名稱和訊息值發出事件。此外,我們在網頁上顯示訊息時向div元素添加了一些樣式。
<!DOCTYPE html> <html> <head> <style> input { width: 300px; margin: 5px auto; padding: 10px; font-size: 20px; border: 3px solid blue; border-radius: 10px; } button { width: 100px; margin: 5px auto; padding: 10px; font-size: 20px; border: 3px solid blue; border-radius: 10px; background-color: aqua; margin: 0 auto; } .message { width: 100%; margin: 0 auto; display: flex; flex-direction: column; justify-content: center; align-items: center; } </style> </head> <body> <h2> Chat App using NodeJS and Socket.io </h2> <!-- creating the input div elements --> <div class = "message"> <input type = "text" id = "name" placeholder = "your name"> <br> <br> <input type = "text" id = "message" placeholder = "your message"> <br> <br> <button id = "send"> Send </button> </div> <br> <br> <br> <div id="messageContent"> </div> </body> <script src="/socket.io/socket.io.js"></script> <script> // initialize the socket on client side let socket = io(); // accessing the input elements let myName = document.getElementById("name"); let myMessage = document.getElementById("message"); let executeSend = document.getElementById("send"); let messageContent = document.getElementById("messageContent"); // adding the click event listener to the send button executeSend.addEventListener("click", (e) => { e.preventDefault(); if (message.value) { // emit the events socket.emit('send name', myName.value); socket.emit('send message', myMessage.value); message.value = ""; } }); //Embedding the name in the div element socket.on("send name", (username) => { let senderName = document.createElement("div"); senderName.style.width = "70%"; senderName.style.color = "green"; senderName.style.textAlign = "center"; senderName.style.backgroundColor = "aqua"; senderName.innerHTML = username + ":"; senderName.style.margin = "5px auto"; senderName.style.fontSize = "30px"; messageContent.appendChild(senderName); }); // embedding the message in the div element socket.on("send message", (chat) => { let message = document.createElement("div"); message.style.width = "70%"; message.style.margin = "5px auto"; message.style.fontSize = "20px"; message.innerHTML = chat; messageContent.appendChild(message); }); </script> </html>
檔名 – App.js
使用者應複製以下程式碼並將其貼上到app.js檔案中。在此程式碼中,我們設定了Node伺服器。此外,我們還使用socket將伺服器與客戶端連線起來。
// Import required libraries const express = require("express"); const http = require("http"); // Initialize the app const app = express(); const { Server } = require("socket.io"); // Create server using http const server = http.createServer(app); const io = new Server(server); // send index.html file to the client app.get("/", (req, res) => { res.sendFile(__dirname + "/index.html"); }); // Listen for the connection event with the client io.on("connection", (socket) => { socket.on("send name", (username) => { io.emit("send name", username); }); socket.on("send message", (chat) => { io.emit("send message", chat); }); }); // run the server on port 3000 const port = 3000; server.listen(port, () => { console.log(`Server is listening at the port: ${port}`); });
使用者可以在終端中執行以下命令來執行Node伺服器。
node app.js
使用者可以在兩個不同的選項卡中開啟https://:3000/ URL,並從一個選項卡傳送訊息。他們可以觀察到第二個選項卡也會收到訊息,因為它充當不同的客戶端。
現在,讓我們瞭解應用程式的流程。因此,每當我們在瀏覽器中開啟https://:3000/ URL時,它都會顯示一個index.html檔案。當我們在輸入值後點擊發送按鈕時,它會從一個客戶端發出“send name”和“send message”事件,其中包含訊息和名稱的值。之後,伺服器接收事件並再次發出相同的事件,以便將訊息和名稱傳送到所有連線的客戶端。
接下來,我們在每個客戶端接收事件並在網頁上顯示訊息。因此,我們需要首先向伺服器傳送訊息才能向所有客戶端傳送訊息。