Home Web Front-end JS Tutorial Use socket to create private and public chat rooms in Node.js_node.js

Use socket to create private and public chat rooms in Node.js_node.js

May 16, 2016 pm 03:31 PM

I will show you the renderings first:

In the previous article, I introduced you to using Angular, Nodejs, and socket.io to build chat rooms and multi-person chat rooms. This article continues to introduce the use of sockets in Node.js to create private and public chat rooms. , please see below for specific details.

Among the applications of nodejs, socket should be more outstanding. socket.io has tens of thousands of stars on github. Its success should not be inferior to express. In order to facilitate the use of the entire socket.io .

For examples, please click http://chat.lovewebgames.com/

Source code downloadhttps://github.com/tianxiangbing/chat

Because I am too poor, the server and database are all free from abroad, and the access speed may be slightly slower.

Let me first talk about my understanding of socket.io. Websocket is more like opening a port service to monitor past communications. So we can rely on the current site port 80 to start the socket service, or we can put it on other ports, such as:

Copy code The code is as follows:

require('socket.io').listen(3000);

This is to monitor port 3000. Since the free server I use does not have permission to open other ports, I still use 80. Since 80 is already used by express, I have to pass it in when express is used. .

Copy code The code is as follows:

var server = http.createServer(app);
var socket = require(‘./socket/msg’)(server);

Then I wrote this in msg.js

Copy code The code is as follows:

var db = require('../db/mysql');
var sio = require('socket.io');
var IO = function(server) {
var io = sio.listen(server)

This is harmonious. db is the method to create a mysql connection, which is not included in this section and is omitted.

This is how it works in socket.io. First, create a connection to the io channel, and then monitor the events of the socket inside. Nodejs is event-driven. The code is as follows:

Copy code The code is as follows:

io.on('connection', function(socket) {
console.log('a user connected.');
​​​​ socket.on('disconnect', function() {
console.log('user disconnected.');
        });
})

As long as a user is connected at this time, it will enter the connection, and its parameter is a socket. If it is a public chat, we can use it directly

Copy code The code is as follows:

io.emit('chat message', {});

This is the form. But we are having a private chat here, so we need to temporarily save this socket object in the global world, so that the person you are chatting with privately can use it to find your socket. This is very convoluted. In fact, the private chat here is not completely point-to-point. It still passes through the server, and the message is transmitted to the server. The server then finds the socket object of the person you want to convey it to and sends it to him. This is the whole process. Here I use an array-like object to store it.

Copy code The code is as follows:

var users = {},
usocket = {};
socket.on('user join', function(data) {
users[username] = username;
usocket[username] = socket;
})

Since I need a username to log in, I use the username as the only identifier (this is just an example, don’t talk to me about duplicate usernames). The advantage of using an array-like form here is that I don’t need to loop. You can also find it quickly. When I send a private message to A, I will first find it in this uscoket, and then call its emit.

function sendUserMsg(data) {
 if (data.to in usocket) {
 console.log('================')
 console.log('to' + data.to, data);
 usocket[data.to].emit('to' + data.to, data);
 usocket[data.user].emit('to' + data.user, data);
 console.log('================')
 }
}
Copy after login

The reason why I emit twice here is that when I send the message to the other party, I also need to receive the message myself and then display it. Why is this? First, the interface is unified, and all the content in the chat comes from the server. Second, it proves that I sent it successfully.

Then when I was listening on the client, I also used my own username to set up an event listener for the username.

socket.on('to' + user, function(data) {
 //console.log(data);
 formatMsg(data);
})
Copy after login

In this way, whether it is a message I send or a message I receive, it will enter this event. Finally, don't forget to delete the object when the user leaves.

socket.on('disconnect', function() {
 console.log('disconnect')
 if (username) {
 counter--;
 delete users[username];
 delete usocket[username];
 if (home.name == username) {
  homeLeave(username);
 }
 sendmsg({
  type: 0,
  msg: "用户<b>" + username + "</b>离开聊天室",
  counter: counter,
  users: users
 })
 }
});
Copy after login

Okay, you’re done.

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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

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.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

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 Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

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.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

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.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

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

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

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

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles