Learn more about how to use the socket in private chat in Nodejs

Source: Internet
Author: User
Tags emit

Learn more about how to use the socket in private chat in Nodejs

In the last time I used nodejs+express+socketio+mysql to build a chat room, which is basically from the Socket.io of the official online tutorial copy learning, and then, according to national conditions, I added a private chat point to point, and then share the paint you draw my guess function.

First on:

Because I am too poor, so the server and database are used abroad for free. The domain name is mine and its access address is: http://chat.lovewebgames.com

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

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

This is to monitor the port 3000, because I use the free server, no permission to open other ports, so, I still use 80, because 80 has been used by express, so I had to express in the use of the time to pass in.

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

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

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

This will be harmonious, DB is the way to create a MySQL connection, not in this section, slightly.

In Socket.io This is the case, first create an IO channel connection, then monitor the socket inside the event, Nodejs is the event driver. 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 there are users connected, it will enter the connection, and then its parameters is a socket, if it is a public chat, we can directly use

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

In this form. But we are here private chat, so we want to temporarily save this socket object in the global, for the object with your private chat to find your socket, very around the mouth, in fact, here private chat, not a complete point-to-point, it is still through the server, the message to the server, The server then finds the person you want to send to the socket object, sent to him. This is the whole process. Here I'm using a class array object to store it.

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

Because I need a username to log in, so I put the user name for the unique identity, and here the advantage of the form of an array of classes is that I can quickly find it without a loop. 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, I have to get the message and show it. One, the interface is unified, the content of the chat is all the server came over, and the other, prove that I sent a successful.

Then when I listen to the client, I also use my own user name as a to+ user name event listener.

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

In this way, whether it is my 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--;d elete Users[username];d elete 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. demo:http://chat.lovewebgames.com/If there is any problem, you can add my QQ group to study together. QQ Technology Group: 5678537,70210212,77813547

Learn more about how to use the socket in private chat in Nodejs

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.