Use socket in Node. js to create private chat and public chat room _ node. js

Source: Internet
Author: User
This article describes how to use socket in Node. js to create private chat rooms and public chat rooms. For more information, see:

In the previous article, we will introduce the use of Angular, Nodejs, and socket. i/O builds chat rooms and multi-user chat rooms. This article continues to introduce Node. use socket in js to create private chat and public chat rooms. For more information, see the following.

In nodejs applications, the socket should be relatively brilliant, socket. i/O has tens of thousands of stars on github, and its success should not be lost in express. In order to facilitate understanding of the entire socket. io usage.

Example please click http://chat.lovewebgames.com/

Source code download https://github.com/tianxiangbing/chat

Because I am too poor, the servers and databases are free of charge abroad, and the access speed may be slightly slower.

Let me first explain my understanding of socket. io. websocket is more like opening a port service to monitor communication in the past. Therefore, we can enable the socket service on port 80 of the current site or on other ports, for example:

The Code is as follows:


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

In this way, port 3000 is monitored. Because the free server I use does not have the permission to open other ports, I still use port 80 because port 80 has been used by express, so I had to pass it in when using express.

The Code is as follows:


Var server = http. createServer (app );
Var socket = require ('./socket/msg') (server );

This is what I wrote in msg. js.

The Code is as follows:


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

In this way, the database is the method for creating a mysql connection, not in this section.

In socket. io, this is the case. First, create an I/O channel connection and then monitor the socket events. nodejs is event-driven. The Code is as follows:

The Code is as follows:


Io. on ('connection', function (socket ){
Console. log ('a user connected .');
Socket. on ('disconnect', function (){
Console. log ('user disconnected .');
});
})

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

The Code is as follows:


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


This form. However, we have a private chat here, so we need to temporarily store this socket object in the global space for you to use it to find your socket for your private chat object. This is actually a private chat here, not completely point-to-point, it still passes through the server, the message is sent to the server, the server then finds the socket object you want to convey to the person, and sends it to him. This is the entire process. Here I am using a class array object for storage.

The Code is as follows:


Var users = {},
Usocket = {};
Socket. on ('user join', function (data ){
Users [username] = username;
Usocket [username] = socket;
})

Because I need to log on with a user name, I use the user name as a unique identifier (this is just an example. Do not talk to me about repeated user names ), the advantage of using an array of classes is that I can quickly find it without loops. When I send A private chat to A, I will first find it in 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('================') }}

Here I am emit twice because I want to receive the message and display it. Why? First, the interface is unified, the content in the chat is all from the server, and second, it proves that I have successfully sent the message.

Then, when I listen on the client, I also use my own user name to initiate a to + User Name event listener.

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

In this way, whether I send a message or I receive a message, this event will occur. Finally, do not forget to delete this 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: "User"+ Username +"Leave the chat room ", counter: counter, users: users })}});

Well, this is all done.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.