Node.js use socket to create private chat and chat room _node.js

Source: Internet
Author: User
Tags emit event listener socket

First to show you the effect of the picture:

In the article for you to introduce the use of angular and Nodejs, Socket.io set up chat rooms and chat rooms, this article continues to introduce node.js use socket to create private chat and chat room, specific details please see below.

Nodejs application, about socket should be more brilliant, socket.io on the GitHub has tens of thousands of people's star, its success should not be lost in Express, in order to facilitate the understanding of the use of the entire socket.io.

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

SOURCE Download Https://github.com/tianxiangbing/chat

Because I am too poor, so the server and database are used abroad for free, access speed can be slightly slow.

First of all, my understanding of Socket.io, websocket more like a port service to monitor the past communication. So we can rely on the current site 80 port open socket service, can also be placed on other ports, such as:

Copy Code code as follows:

Require (' Socket.io '). Listen (3000);

This is to monitor the 3000 port, because I use the free server, do not have permission to open other ports, so I still use 80, because 80 has been express use, so I had to express the use of the time passed in.

Copy Code code as follows:

var server = Http.createserver (APP);
var socket = require ('./socket/msg ') (server);

And that's what I wrote in the Msg.js.

Copy Code code as follows:

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

In this way, DB is the way to create a MySQL connection, not in this section, slightly.

In Socket.io, this is the first to create an IO channel connection, and then monitor the inside of the socket event, Nodejs is the event driver. The code is as follows:

Copy Code code as follows:

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

At this point, as long as the user connected, will enter the connection, and then its parameters is a socket, if it is public chat, we can directly use

Copy Code code as follows:

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



This form again. But we have a private conversation here. So we have to temporarily save this socket object in the overall situation, for your private chat with the object to use to find your socket, very around the mouth, in fact, the private chat here, not a complete point-to-point, it still passed the server, the message 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 whole process. Here I'm using a class array object to store.

Copy Code code 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 put the user's masterpiece for a unique identity (this is just an example, don't talk to me about user name duplication), the advantage of using an array of classes is that I can find it quickly without looping. When I send a private chat 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 (' ================ ')
 }
}

The reason I emit two times here is that when I send the message to the other side, I have to get the message myself and then show it, why? First, the interface is unified, the content of the chat is all over the server, and the second, prove that I sent success.

Then when I listen to the client, I also use my own username as an event listener with a to+ username.

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

So, whether I send the message, or I received the message, will enter the 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: "User <b>" + username + "</b> leave chat room",
  counter:counter,
  users: Users
 }}
);

Well, that's it.

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.