Nodejs combines Socket.IO to realize instant messaging function
This article mainly introduces the instant messaging function implemented by nodejs combined with Socket.IO. It analyzes the relevant operating skills and precautions of nodejs combined with Socket.IO to implement instant messaging in detail in the form of examples. Friends who need it can refer to it. I hope it can help. Everyone.
Dynamic web
Before HTML5, web design did not consider dynamics. It was always designed around documents. We Looking at the older websites in the past, they were basically used to display a single document at a certain moment. The user requested a web page once and obtained a page. However, as time goes by, people want the web to do more things, and Rather than simply displaying documents, JavaScript has been at the center of how developers have pushed the functionality of web pages.
Ajax is undoubtedly a major development in dynamic Web pages. It no longer requires us to refresh the entire page even if we update a little content. However, in some aspects, it reflects its shortcomings. It's okay if you request data from the server, but what if the server wants to push data to the browser. Ajax technology cannot easily support pushing data to customers. Although it can, it requires many cross-border obstacles, and different browsers work differently. For example, IE and FireBox have different kernels, so their working methods are also different. no the same.
WebSocket is a response to the problem of two-way communication between the server and the client. The idea was to start from the ground up and design a standard that developers could use to create applications in a consistent way, rather than going through complicated settings that didn't always work in all browsers. The idea is to keep a persistent open connection between the web server and the browser, so that both the server and the browser can push data when they want. Because the connection is persistent, the exchange of data is very fast and becomes real-time.
Socket.IO
Having said so much, let’s introduce the author. Socket.IO is a module of Node.js. He Provides a simple way to communicate through WebSocket. The WebSocket protocol is complex, but Socket.IO provides components for both the server and the client, so only one module is needed to add support for WebSocket to the application. It also supports different browsers.
Basic Socket.IO
Socket.IO can work on both the server and the client. To use it, you must add it to the server-side JavaScript (Node.js) and client-side JavaScript (JQuery), this is because internal communication is usually bidirectional, so Sokcet.IO needs to be able to work on both sides.
var server = http.createServer(function (req,res){ fs.readFile('./index.html',function(error,data){ res.writeHead(200,{'Content-Type':'text/html'}); res.end(data,'utf-8'); }); }).listen(3000,"127.0.0.1"); console.log('Server running at http://127.0.0.1:3000/');
And the Socket.IO library must be included to add the Socket.IO function.
var io = require('socket.io').listen(server);
Then add an event to respond to whether the client is connected or disconnected. The event is as follows:
io.sockets.on('connection',function(socket){ console.log('User connected'); socket.on('disconnect',function(){ console.log('User disconnected'); }); });
Do you think it is very simple? Let’s take a look at how the complete code implementation is implemented:
Simple Socket.IO application
New app.js
Create a new folder socket.io, and create a new app under this folder. js, write the following code:
var http = require('http'); var fs = require('fs'); var server = http.createServer(function (req,res){ fs.readFile('./index.html',function(error,data){ res.writeHead(200,{'Content-Type':'text/html'}); res.end(data,'utf-8'); }); }).listen(3000,"127.0.0.1"); console.log('Server running at http://127.0.0.1:3000/'); var io = require('socket.io').listen(server); io.sockets.on('connection',function(socket){ console.log('User connected'); socket.on('disconnect',function(){ console.log('User disconnected'); }); });
New index.html
Create a new index.html file, the code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Socket.IO Example</title> </head> <body> <h1 id="Socket-IO-nbsp-Example">Socket.IO Example</h1> <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://127.0.0.1:3000'); </script> </body> </html>
Create new package.json
Create new package.json to introduce the module.
{ "name":"socketio_example", "version":"4.13.2", "private":true, "dependencies":{ "socket.io":"1.4.5" } }
Version number You can enter your own nodejs -V, or socket.io -v to check your version number.
Run
If you have not installed Socket.IO, you can run the following code. If you have installed it, this step will be skipped automatically.
npm install socket.io
Run the following command from the terminal to install the module
npm install
Run the following command to start the server
node app.js
Open the browser, enter http://127.0.0.1:3000/, open a few more tabs, enter the URL in each, then close any tab, and then take a look at our Is the cmd command window as follows:
Here will be recorded in detail how many users are used to connect and how many users are disconnected, so that we can count our web pages of visits.
Sending data from the server to the client
In the above example, we have already implemented the connection or disconnection of the server for recording, but if we What should we do if we want to push messages? For example, if our friend's QQ is online, Tencent will cough to remind us that our friend is online. Let's take a look at this function.
Send to a single user
io.sockets.on('connection',function(socket){ socket.emit('message',{text:'你上线了'}); });
Send to all users
io.sockets.on('connection',function(socket){ socket.broadcast.emit('message',{'你的好某XXX上线了'}); });
Whether it is sent to a single user or all users, this message is written by yourself, but it needs to be used on the client, so pay attention to the naming.
Client
在客户端我们可以添加侦听事件来接收数据。
var socket = io.connect('http://127.0.0.1:3000'); socket.on('message',function(data){ alert(data.text); })
通过这些功能,我们就在第一个例子的基础上,实现用户数量的统计。这里只需要在服务端设置一个变量,count,如果有一个上线,那么就数量+1,并通知所有用户,最新的在线人数。
新建app.js
var http = require('http'); var fs = require('fs'); var count = 0; var server = http.createServer(function (req,res){ fs.readFile('./index.html',function(error,data){ res.writeHead(200,{'Content-Type':'text/html'}); res.end(data,'utf-8'); }); }).listen(3000,"127.0.0.1"); console.log('Server running at http://127.0.0.1:3000/'); var io = require('socket.io').listen(server); io.sockets.on('connection',function(socket){ count++; console.log('User connected' + count + 'user(s) present'); socket.emit('users',{number:count}); socket.broadcast.emit('users',{number:count}); socket.on('disconnect',function(){ count--; console.log('User disconnected'); socket.broadcast.emit('users',{number:count}); }); });
创建index.html文件
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Socket.IO Example</title> </head> <body> <h1 id="Socket-IO-nbsp-Example">Socket.IO Example</h1> <h2 id="How-nbsp-many-nbsp-users-nbsp-are-nbsp-here">How many users are here?</h2> <p id="count"></p> <script src="http://***.***.**.***:9001/jquery.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://127.0.0.1:3000'); var count = document.getElementById('count'); socket.on('users',function(data){ console.log('Got update from the server'); console.log('There are ' + data.number + 'users'); count.innerHTML = data.number }); </script> </body> </html>
创建package.json文件
{ "name":"socketio_example", "version":"4.13.2", "private":true, "dependencies":{ "socket.io":"1.4.5" } }
安装模块npm install
启动服务器node app.js
打开浏览器,输入http://127.0.0.1:3000,可以看到如下图片:
再打开一个连接http://127.0.0.1:3000,可以看到如下结果:
可以看到如果我们打开两个连接,那么两个页签都会显示当前又两个用户在线,如果关闭其中一个,我们可以看到又显示只有一个用户在线。
将数据广播给客户端
接下来我们来看看Socket.IO是如何实现客户端与客户端的通信呢。
要想实现该功能,首先需要客户端将消息发送到服务端,·然后服务端发送给除自己之外的其他客户。服务器将消息发送给客户端的方法在上一个例子中我们已经实现了,那么我们需要的是客户端把接收到的消息发送给服务器。
下边的代码思想是利用表单来实现的。
<form id="message-form" action="#"> <textarea id="message" rows="4" cols="30"></textarea> <input type="submit" value="Send message" /> </form> <script src="http://***.***.***.**:9001/jquery.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://127.0.0.1:3000'); var message = document.getElementById('message'); $(message.form).submit(function() { socket.emit('message', { text: message.value }); return false; }); socket.on('push message', function (data) { $('form').after('<p>' + data.text + '</p>'); }); </script>
实现的思想是,将JQuery和SocketIO库包含进来,只是浏览器拦截127.0.0.1:3000的服务,使用Jquery的submit方法加入侦听期,等候用户提交表单。
发送消息给Socket>IO服务器,文本区域的内容位消息发送。
添加return false ,防止表单在浏览器窗口提交。
在上边已经说过服务器如何广播消息,下边我们说一下客户端如何显示客户端发送的消息。
socket.on('push message', function (data) { $('form').after('<p>' + data.text + '</p>'); })
实例实现
创建messaging的新文件夹
在文件夹下创建package.json文件,代码如下:
{ "name":"socketio_example", "version":"4.13.2", "private":true, "dependencies":{ "socket.io":"1.4.5" } }
创建app.js文件,代码如下:
var http = require('http'); var fs = require('fs'); var server = http.createServer(function (req,res){ fs.readFile('./index.html',function(error,data){ res.writeHead(200,{'Content-Type':'text/html'}); res.end(data,'utf-8'); }); }).listen(3000,"127.0.0.1"); console.log('Server running at http://127.0.0.1:3000/'); var io = require('socket.io').listen(server); io.sockets.on('connection',function(socket){ socket.on('message',function(data){ socket.broadcast.emit('push message',data); }); });
创建index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Socket.IO Example</title> </head> <body> <h1 id="Socket-IO-nbsp-Example">Socket.IO Example</h1> <form id="message-form" action="#"> <textarea id="message" rows="4" cols="30"></textarea> <input type="submit" value="Send message" /> </form> <script src="http://222.222.124.77:9001/jquery.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://127.0.0.1:3000'); var message = document.getElementById('message'); $(message.form).submit(function() { socket.emit('message', { text: message.value }); return false; }); socket.on('push message', function (data) { $('form').after('<p>' + data.text + '</p>'); }); </script> </body> </html>
加载模块npm install
启动服务器node app.js
然后打开浏览器的多个页签,都输入http://127.0.0.1:3000
可以看到我们再任何一个窗口输入内容,都会在其他的页面显示我们输入的内容,效果如下:
小结
这篇博客好长,其实说了这么多,还是有很多的东西没有说,但是我们还是讨论了Socket.IO如何实现动态的,通过服务端能显示用户的连接,和统计链接次数统计,到最后的消息的通知和聊天功能的实现。在我们的生活中这种例子比比解释,例如QQ,例如淘宝的抢购,都是可以通过这种方式实现的,这样我们就能实时的实现动态的功能了。
相关推荐:
HTML5+NodeJs实现WebSocket即时通讯的示例代码分享
Workerman+layerIM+ThinkPHP5的webIM,即时通讯系统
The above is the detailed content of Nodejs combines Socket.IO to realize instant messaging function. For more information, please follow other related articles on the PHP Chinese website!

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.