Live chat using NodeJS, Socket.io and ExpressJS
Aug 29, 2023 pm 12:49 PMNodeJS allows me to write backend code in one of my favorite languages: JavaScript. It is the perfect technology for building real-time applications. In this tutorial, I'll show you how to build a web chat application using ExpressJS and Socket.io.
Set up environment
Of course, the first thing to do is to install NodeJS on your system. If you are a Windows or Mac user, you can visit nodejs.org and download the installer. If you prefer Linux, I recommend you refer to this link. While I won't go into detail on this, if you run into any installation issues I'd be happy to help; just leave a comment below this article.
After installing NodeJS, you can set up the required tools.
- ExpressJS - This will manage the server and responses to the user
- Jade - Template Engine
- Socket.io - allows real-time communication between frontend and backend
Continue, create a package.json file in an empty directory containing the following content.
{ "name": "RealTimeWebChat", "version": "0.0.0", "description": "Real time web chat", "dependencies": { "socket.io": "latest", "express": "latest", "jade": "latest" }, "author": "developer" }
By using the console (in Windows - Command Prompt), navigate to your folder and execute:
npm install
Within a few seconds, you will have all required dependencies downloaded into the node_modules directory.
Developing backend
Let’s start with a simple server that will serve the application’s HTML pages, and then move on to the more interesting part: real-time communication. Create an index.js file using the following core expressjs code:
var express = require("express"); var app = express(); var port = 3700; app.get("/", function(req, res){ res.send("It works!"); }); app.listen(port); console.log("Listening on port " + port);
Above, we created an application and defined its port. Next, we register a route, which in this case is a simple GET request without any parameters. Currently, the route's handler just sends some text to the client. Finally, of course, at the bottom, we run the server. To initialize the application, execute from the console:
node index.js
The server is running, so you should be able to open http://127.0.0.1:3700/ and see:
It works!
Now, instead of "it works", we should provide HTML. It might be more beneficial to use a template engine instead of plain HTML. Jade is a great choice and has great integration with ExpressJS. This is what I usually use in my own projects. Create a directory called tpl and place the following page.jade file into it:
!!! html head title= "Real time web chat" body #content(style='width: 500px; height: 300px; margin: 0 0 20px 0; border: solid 1px #999; overflow-y: scroll;') .controls input.field(style='width:350px;') input.send(type='button', value='send')
The syntax of Jade is not complicated, however, for a complete guide, I recommend you to refer to jade-lang.com. In order to use Jade with ExpressJS we need to set up the following.
app.set('views', __dirname + '/tpl'); app.set('view engine', "jade"); app.engine('jade', require('jade').__express); app.get("/", function(req, res){ res.render("page"); });
This code tells Express where your template files are located and which template engine to use. It all specifies the function that will handle the template code. Once everything is set up, we can use the response
object's .render
method and send our Jade code to the user.
The output at this point is nothing special; it's nothing more than a div
element (the one with the id content
), which will serve as a container for the chat message and two controls (the input field and the button ), we will use them to send messages. p>
Because we will be using an external JavaScript file to hold the front-end logic, we need to tell ExpressJS where to look for such resources. Create an empty directory public
and add the following lines before calling the .listen
method.
app.use(express.static(__dirname + '/public'));
So far so good; we have a server that successfully responds to GET requests. Now, it's time to add Socket.io integration. Change this line:
app.listen(port);
to:
var io = require('socket.io').listen(app.listen(port));
Above, we passed the ExpressJS server to Socket.io. In fact, our live communication will still happen on the same port.
Next, we need to write the code that receives messages from the client and sends them to all other clients. Every Socket.io application starts with a connection
handler. We should have one:
io.sockets.on('connection', function (socket) { socket.emit('message', { message: 'welcome to the chat' }); socket.on('send', function (data) { io.sockets.emit('message', data); }); });
The object passed to the handler socket
is actually the client's socket. Think of it as the connection point between the server and the user's browser. Once the connection is successful, we send a message of type welcome
and, of course, bind another handler that will act as a receiver. As a result, the client should issue a message named send
, which we will capture. Next, we simply use io.sockets.emit
to forward the data sent by the user to all other sockets.
With the above code, our backend is ready to receive and send messages to the client. Let's add some front-end code.
Developing front-end
Create chat.js
and place it in the public
directory of your application. Paste the following code:
window.onload = function() { var messages = []; var socket = io.connect('http://localhost:3700'); var field = document.getElementById("field"); var sendButton = document.getElementById("send"); var content = document.getElementById("content"); socket.on('message', function (data) { if(data.message) { messages.push(data.message); var html = ''; for(var i=0; i<messages.length; i++) { html += messages[i] + '<br />'; } content.innerHTML = html; } else { console.log("There is a problem:", data); } }); sendButton.onclick = function() { var text = field.value; socket.emit('send', { message: text }); }; }
我們的邏輯包裝在 .onload
處理程序中,只是為了確保所有標(biāo)記和外部 JavaScript 均已完全加載。在接下來(lái)的幾行中,我們創(chuàng)建一個(gè)數(shù)組,它將存儲(chǔ)所有消息、一個(gè) socket
對(duì)象以及一些 DOM 元素的快捷方式。同樣,與后端類(lèi)似,我們綁定一個(gè)函數(shù),它將對(duì)套接字的活動(dòng)做出反應(yīng)。在我們的例子中,這是一個(gè)名為 message
的事件。當(dāng)此類(lèi)事件發(fā)生時(shí),我們期望收到一個(gè)對(duì)象,data,其屬性為 message
。將該消息添加到我們的存儲(chǔ)中并更新 content
div
。我們還包含了發(fā)送消息的邏輯。這非常簡(jiǎn)單,只需發(fā)出一條名為 send 的消息。
如果你打開(kāi)http://localhost:3700,你會(huì)遇到一些錯(cuò)誤彈出窗口。這是因?yàn)槲覀冃枰?page.jade
以包含必要的 JavaScript 文件。
head title= "Real time web chat" script(src='/chat.js') script(src='/socket.io/socket.io.js')
請(qǐng)注意,Socket.io 管理 socket.io.js 的交付。您不必?fù)?dān)心手動(dòng)下載此文件。
我們可以在控制臺(tái)中使用 node index.js
再次運(yùn)行我們的服務(wù)器并打開(kāi)http://localhost:3700。您應(yīng)該會(huì)看到歡迎消息。當(dāng)然,如果你發(fā)送一些東西,應(yīng)該顯示在內(nèi)容的div
中。如果您想確保它有效,請(qǐng)打開(kāi)一個(gè)新選項(xiàng)卡(或者更好的是,一個(gè)新瀏覽器)并加載應(yīng)用程序。 Socket.io 的偉大之處在于,即使您停止 NodeJS 服務(wù)器它也能工作。前端將繼續(xù)工作。一旦服務(wù)器再次啟動(dòng),您的聊天也會(huì)正常。
在目前的狀態(tài)下,我們的聊天并不完美,需要一些改進(jìn)。
改進(jìn)
我們需要做的第一個(gè)更改是消息的標(biāo)識(shí)。目前,尚不清楚哪些消息是由誰(shuí)發(fā)送的。好處是我們不必更新 NodeJS 代碼來(lái)實(shí)現(xiàn)這一點(diǎn)。這是因?yàn)榉?wù)器只是轉(zhuǎn)發(fā) data
對(duì)象。因此,我們需要在那里添加一個(gè)新屬性,并稍后讀取它。在對(duì) chat.js
進(jìn)行更正之前,讓我們添加一個(gè)新的 input
字段,用戶可以在其中添加他/她的姓名。在 page.jade
中,更改 controls
div
:
.controls | Name: input#name(style='width:350px;') br input#field(style='width:350px;') input#send(type='button', value='send')
接下來(lái),在code.js中:
window.onload = function() { var messages = []; var socket = io.connect('http://localhost:3700'); var field = document.getElementById("field"); var sendButton = document.getElementById("send"); var content = document.getElementById("content"); var name = document.getElementById("name"); socket.on('message', function (data) { if(data.message) { messages.push(data); var html = ''; for(var i=0; i<messages.length; i++) { html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>'; html += messages[i].message + '<br />'; } content.innerHTML = html; } else { console.log("There is a problem:", data); } }); sendButton.onclick = function() { if(name.value == "") { alert("Please type your name!"); } else { var text = field.value; socket.emit('send', { message: text, username: name.value }); } }; }
為了總結(jié)這些變化,我們:
- 為用戶名的
input
字段添加了新快捷方式 - 稍微更新了消息的呈現(xiàn)方式
- 向?qū)ο筇砑恿艘粋€(gè)新的
username
屬性,該屬性將發(fā)送到服務(wù)器
如果消息數(shù)量過(guò)多,用戶將需要滾動(dòng) div
:
content.innerHTML = html; content.scrollTop = content.scrollHeight;
請(qǐng)記住,上述解決方案可能不適用于 IE7 及更低版本,但沒(méi)關(guān)系:IE7 是時(shí)候消失了。但是,如果您想確保支持,請(qǐng)隨意使用 jQuery:
$("#content").scrollTop($("#content")[0].scrollHeight);
如果發(fā)送消息后輸入字段被清除,那就太好了:
socket.emit('send', { message: text, username: name.value }); field.value = "";
最后一個(gè)無(wú)聊的問(wèn)題是每次點(diǎn)擊發(fā)送按鈕。通過(guò)一點(diǎn) jQuery,我們可以監(jiān)聽(tīng)用戶何時(shí)按下 Enter
鍵。
$(document).ready(function() { $("#field").keyup(function(e) { if(e.keyCode == 13) { sendMessage(); } }); });
可以注冊(cè)函數(shù) sendMessage
,如下所示:
sendButton.onclick = sendMessage = function() { ... };
請(qǐng)注意,這不是最佳實(shí)踐,因?yàn)樗?cè)為全局函數(shù)。但是,對(duì)于我們?cè)谶@里的小測(cè)試來(lái)說(shuō),一切都很好。
結(jié)論
NodeJS 是一項(xiàng)非常有用的技術(shù),它為我們提供了巨大的力量和樂(lè)趣,特別是考慮到我們可以編寫(xiě)純 JavaScript 的事實(shí)。正如您所看到的,僅用幾行代碼,我們就編寫(xiě)了一個(gè)功能齊全的實(shí)時(shí)聊天應(yīng)用程序。非常整潔!
想要了解有關(guān)使用 ExpressJS 構(gòu)建 Web 應(yīng)用程序的更多信息?我們?yōu)槟?wù)!
The above is the detailed content of Live chat using NodeJS, Socket.io and ExpressJS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

Node.js is suitable for the following project types: Network and server applications Event-driven applications Real-time applications Data-intensive applications Command-line tools and scripts Lightweight microservices

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application
