Home > Web Front-end > JS Tutorial > How to implement instant messaging using nodejs

How to implement instant messaging using nodejs

亚连
Release: 2018-06-12 12:10:08
Original
3356 people have browsed it

This article mainly introduces the instant messaging function implemented by nodejs combined with Socket.IO. It analyzes the related operating skills and precautions of nodejs combined with Socket.IO to implement instant messaging in detail in the form of examples. Friends in need can refer to the following

The example in this article describes the instant messaging function implemented by nodejs combined with Socket.IO. Share it with everyone for your reference, the details are as follows:

dynamic web

Before HTML5, dynamics were not considered in the design of the web. It has always been designed around documents. We see that older websites in the past were basically used to display a single document at a certain moment. The user requests a web page once and gets a page. But as time goes by, people want to The web has to do more than simply display documents, and JavaScript has been at the center of developers' efforts to push 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/');
Copy after login

And the Socket.IO library must be included to add the Socket.IO function.

var io = require('socket.io').listen(server);
Copy after login

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');
  });
});
Copy after login

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, create a new app.js under this folder, and 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');
  });
});
Copy after login

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>Socket.IO Example</h1>
  <script src="/socket.io/socket.io.js"></script>
  <script>
   var socket = io.connect(&#39;http://127.0.0.1:3000&#39;);
  </script>
 </body>
</html>
Copy after login

New package.json

Create a new package.json to introduce the module.

{
  "name":"socketio_example",
  "version":"4.13.2",
  "private":true,
  "dependencies":{
    "socket.io":"1.4.5"
  }
}
Copy after login
Copy after login
Copy after login

For the 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
Copy after login

Run the following command from the terminal to install the module

npm install
Copy after login

Run the following command to start the server

node app.js
Copy after login

Open the browser and enter http://127.0.0.1:3000/, more Open several tabs, enter the URL in each, and then close any tab, and then see if our cmd command window is as follows:

will be recorded in detail here How many are used to connect and how many users are disconnected, so that we can count the number of visits to our web page.

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(&#39;connection&#39;,function(socket){
    socket.emit(&#39;message&#39;,{text:&#39;你上线了&#39;});
});
Copy after login

Send to all users

io.sockets.on(&#39;connection&#39;,function(socket){
    socket.broadcast.emit(&#39;message&#39;,{&#39;你的好某XXX上线了&#39;});
});
Copy after login

Whether it is sent to a single user or all users, This message is written by myself, but it needs to be used on the client, so pay attention to the naming.

Client

On the client side we can add listening events to receive data.

var socket = io.connect(&#39;http://127.0.0.1:3000&#39;);
socket.on(&#39;message&#39;,function(data){
  alert(data.text);
})
Copy after login

通过这些功能,我们就在第一个例子的基础上,实现用户数量的统计。这里只需要在服务端设置一个变量,count,如果有一个上线,那么就数量+1,并通知所有用户,最新的在线人数。

新建app.js

var http = require('http');
var fs = require('fs');
var count = 0;
var server = http.createServer(function (req,res){
  fs.readFile(&#39;./index.html&#39;,function(error,data){
    res.writeHead(200,{&#39;Content-Type&#39;:&#39;text/html&#39;});
    res.end(data,&#39;utf-8&#39;);
  });
}).listen(3000,"127.0.0.1");
console.log(&#39;Server running at http://127.0.0.1:3000/&#39;);
var io = require(&#39;socket.io&#39;).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});
  });
});
Copy after login

创建index.html文件

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title>Socket.IO Example</title>
 </head>
 <body>
  <h1>Socket.IO Example</h1>
  <h2>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(&#39;http://127.0.0.1:3000&#39;);
   var count = document.getElementById(&#39;count&#39;);
   socket.on(&#39;users&#39;,function(data){
    console.log(&#39;Got update from the server&#39;);
    console.log(&#39;There are &#39; + data.number + &#39;users&#39;);
    count.innerHTML = data.number
   });
  </script>
 </body>
</html>
Copy after login

创建package.json文件

{
  "name":"socketio_example",
  "version":"4.13.2",
  "private":true,
  "dependencies":{
    "socket.io":"1.4.5"
  }
}
Copy after login
Copy after login
Copy after login

安装模块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(&#39;http://127.0.0.1:3000&#39;);
   var message = document.getElementById(&#39;message&#39;);
   $(message.form).submit(function() {
    socket.emit(&#39;message&#39;, { text: message.value });
    return false;
   });
   socket.on(&#39;push message&#39;, function (data) {
    $(&#39;form&#39;).after(&#39;<p>&#39; + data.text + &#39;</p>&#39;);
   });
</script>
Copy after login

实现的思想是,将JQuery和SocketIO库包含进来,只是浏览器拦截127.0.0.1:3000的服务,使用Jquery的submit方法加入侦听期,等候用户提交表单。

发送消息给Socket>IO服务器,文本区域的内容位消息发送。

添加return false ,防止表单在浏览器窗口提交。

在上边已经说过服务器如何广播消息,下边我们说一下客户端如何显示客户端发送的消息。

socket.on(&#39;push message&#39;, function (data) {
  $(&#39;form&#39;).after(&#39;<p>&#39; + data.text + &#39;</p>&#39;);
})
Copy after login

实例实现

创建messaging的新文件夹

在文件夹下创建package.json文件,代码如下:

{
  "name":"socketio_example",
  "version":"4.13.2",
  "private":true,
  "dependencies":{
    "socket.io":"1.4.5"
  }
}
Copy after login
Copy after login
Copy after login

创建app.js文件,代码如下:

var http = require('http');
var fs = require('fs');
var server = http.createServer(function (req,res){
  fs.readFile(&#39;./index.html&#39;,function(error,data){
    res.writeHead(200,{&#39;Content-Type&#39;:&#39;text/html&#39;});
    res.end(data,&#39;utf-8&#39;);
  });
}).listen(3000,"127.0.0.1");
console.log(&#39;Server running at http://127.0.0.1:3000/&#39;);
var io = require(&#39;socket.io&#39;).listen(server);
io.sockets.on('connection',function(socket){
  socket.on('message',function(data){
    socket.broadcast.emit('push message',data);
  });
});
Copy after login

创建index.html

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="utf-8" />
  <title>Socket.IO Example</title>
 </head>
 <body>
  <h1>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(&#39;http://127.0.0.1:3000&#39;);
   var message = document.getElementById(&#39;message&#39;);
   $(message.form).submit(function() {
    socket.emit(&#39;message&#39;, { text: message.value });
    return false;
   });
   socket.on(&#39;push message&#39;, function (data) {
    $(&#39;form&#39;).after(&#39;<p>&#39; + data.text + &#39;</p>&#39;);
   });
  </script>
 </body>
</html>
Copy after login

加载模块npm install

启动服务器node app.js

然后打开浏览器的多个页签,都输入http://127.0.0.1:3000

可以看到我们再任何一个窗口输入内容,都会在其他的页面显示我们输入的内容,效果如下:

小结

这篇博客好长,其实说了这么多,还是有很多的东西没有说,但是我们还是讨论了Socket.IO如何实现动态的,通过服务端能显示用户的连接,和统计链接次数统计,到最后的消息的通知和聊天功能的实现。在我们的生活中这种例子比比解释,例如QQ,例如淘宝的抢购,都是可以通过这种方式实现的,这样我们就能实时的实现动态的功能了。尤其是12306这个网站,我得和他们说说了,哈哈。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

有关ejsExcel模板使用方法

在D3.js中如何创建物流地图(详细教程)

在javascript中如何获取图片的top N主色值

在Angular中利用trackBy如何提升性能

在微信小程序中如何实现翻牌小游戏

The above is the detailed content of How to implement instant messaging using nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template