Home Web Front-end JS Tutorial Detailed explanation of node.js + socket.io implementing chat function

Detailed explanation of node.js + socket.io implementing chat function

Jul 02, 2017 am 10:17 AM
javascript node.js socket.io

This article mainly introduces node.js + socket.io to implement point-to-point random matching chat, which has certain reference value. Interested friends can refer to it

Sincerely I admire those who can often post notes. In fact, I also want to send them often. However, I am not skilled enough and am lazy. I need to learn more from the masters. Some time ago, I used the socket that comes with the bomb platform to write a chat room. In fact, it is basically I changed its demo. This time I wanted to implement a random private chat, so I built the service based on node and socket.io. Of course, this is my first time using node to make something. Although I didn’t do it well, I still want to share it. ha.

Let’s first talk about the things used. node is used for background services, express is used to host static resources, and socket.io is used to transmit chat data. Next, let’s talk about the idea. In fact, it is very simple to use socket.io to transmit data. We only need to introduce socket.io.js on the front-end page and then do it on the node side. require('socket. io'), run it on the backend, then the frontend can send or receive information through the following code.


//前端
socket = io.connect('ws://'+'服务器ip');
socket.emit('msg',{msg:'前端要发送的信息'});//要发送的信息(以对象的形式发送)
socket.on('msg2',function(data){
  ...
  //这里的data是后端传过来的信息
})
//后端
socket.on('msg',function(data){
  var data = data; //这里的data就是前端传过来的数据,即{msg:'前端要发送的信息'}
  console.log(data.msg) // 打印出 “前端要发送的信息”
})
//同理,后端要传信息给前端也是一样
socket.emit('msg2',{msg:'后端要发送的信息'});
Copy after login

Let’s see how the backend runs the socket


 var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){ //当前端执行 socket = io.connect('ws://'+host); 的时候,此处的io会监听到connection事件
 socket.on('msg',function(data){ 
 io.emit('onlineCount',freeList)
 //如果直接用io.emit来发送数据的话,这代表广播的形式,就是当前所有打开服务的前端页面都会收到这条消息。
 
   socket.emit('welcome',{msg:'欢迎...'})//这里将给当前连接的页面发送一个欢迎的对象数据
 })
 socket.on('disconnect',function(){
 //当前端页面关闭,或者失去连接时,后端会接收到disconnect事件
   
 })

})
http.listen(4000, function(){
 console.log('listening on *:4000');
});
Copy after login

Of course it’s not just that, because of the websocket protocol, A long link is established between the browser and the server to transmit data to each other. For the server, if several pages are opened, there will be several socket instances. Each front-end page that establishes a connection will have a socket instance. , which provides ideas for the subsequent peer-to-peer private chat. Of course, we can also send information via direct broadcast, but this is suitable for chat room scenarios.

How to implement point-to-point? As mentioned before, each page that establishes a connection will generate a socket instance, so we only need the backend to judge while receiving the message Whichever instance the socket instance is chatting with, just send the message to another matching socket instance. To put it simply, it's like writing a letter. I send the message to the backend, and then tell the backend that the message is for xxx. Then the backend finds the socket instance corresponding to xxx and sends the message to him.


//前端
window.id = new Date().getTime()+""+Math.floor(Math.random()*899+100);
//每次登录,获取一个唯一的用户id
socket = io.connect('ws://'+host);
socket.emit('newUser',{ user_name : name, user_id : id})
//建立连接后,将我的用户名和id都传给后端

//后端
socket.on('newUser',function(data){
 var nickname = data.user_name,
  user_id = data.user_id;
 userServer[user_id] = socket;
 //后端接收后,将该用户socket保存在一个对象里,key值为id,value就是这个用户的socket
  
})
Copy after login

Through the above code, the backend gets a userServer object, which contains the corresponding value of each connection socket and its id. In this way, you can Point-to-point data transmission is achieved by attaching the ID of the object to be received each time a message is sent.

The next step is data processing, how to get the other party’s ID, etc. In view of my limited expression ability and laziness, I won’t go into details~~ I host the code on github. Welcome yourself. Come down and take a look

The above is the detailed content of Detailed explanation of node.js + socket.io implementing chat function. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles