Nodejs implements a simple chat room function sharing _ node. js

Source: Internet
Author: User
Tags sendmsg
This article mainly introduces a simple chat room function implemented by nodejs. This article uses express and socket. i/O libraries can be implemented in combination. For more information about how to implement a simple chat room today, nodejs is used in the background, and socket is used for communication between the client and the server. io, which is a mature websocket framework.

Initial work

1. install express. Use this to host socket. io and static pages. Run the npm install express -- save and -- save command to add the package to the package. json file.
2. install socket. io and run npm install socket. io -- save.

Write server code

First, we host the website through express and attach it to the socket. io instance, because the first connection to socket. io requires the http protocol

The Code is as follows:


Var express = require ('express '),
Io = require ('socket. io ');

Var app = express ();

App. use (express. static (_ dirname ));

Var server = app. listen (8888 );


Var ws = io. listen (server );


Add a server connection event. After the client connection is successful, an announcement will be issued to all online users. When a user sends a message, a broadcast will be sent to other users.

The Code is as follows:


Ws. on ('connection', function (client ){
Console. log ('\ 033 [96 msomeone is connect \ 033 [39 m \ n ');
Client. on ('join', function (msg ){
// Check whether there are duplicates
If (checkNickname (msg )){
Client. emit ('nickname', 'duplicate nicknames! ');
} Else {
Client. nickname = msg;
Ws. sockets. emit ('announcement ', 'system', msg +' joined the chat room! ');
}
});
// Listen for messages sent
Client. on ('send. message', function (msg ){
Client. broadcast. emit ('send. message', client. nickname, msg );
});
// Notify other users when the connection is disconnected
Client. on ('disconnect', function (){
If (client. nickname ){
Client. broadcast. emit ('send. message', 'system', client. nickname + 'leave the chat room! ');
}
})

})

Because the client is identified by a nickname, the server needs a function to detect duplicate nicknames.

The Code is as follows:


// Check whether the nickname is repeated
Var checkNickname = function (name ){
For (var k in ws. sockets. sockets ){
If (ws. sockets. sockets. hasOwnProperty (k )){
If (ws. sockets. sockets [k] & ws. sockets. sockets [k]. nickname = name ){
Return true;
}
}
}
Return false;
}

Write client code

Because the server uses a third-party websokcet framework, the front-end page must reference socket separately. io client code, the source file can be from socket. find in the io module. In windows, the path is node_modules \ socket. io \ node_modules \ socket. io-client \ dist. The developer and compressed versions are available here. By default, the developer version can be referenced.

The front-end mainly processes the input nickname check and message processing. The complete code is as follows:

The Code is as follows:





Socket. io chat room example













Clear Screen
Send



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.