Detailed explanation of node.js + socket.io implementing chat function
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:'后端要发送的信息'});
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'); });
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 })
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!

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


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

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

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.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
