Home > Web Front-end > JS Tutorial > Sharing a simple chat room function implemented in nodejs_node.js

Sharing a simple chat room function implemented in nodejs_node.js

WBOY
Release: 2016-05-16 16:28:46
Original
1489 people have browsed it

Today I will implement a simple chat room, using nodejs in the background, and socket.io to communicate between the client and the server. This is a relatively mature websocket framework.

Initial work

1. Install express and use it to host socket.io and static pages. Command npm install express --save, --save to add the package to the package.json file.
2. Install socket.io, command npm install socket.io --save.

Write server code

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

Copy code 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. When the client connection is successful, an announcement will be sent to all online users. When a user sends a message, a broadcast will be sent to notify other users.
Copy code The code is as follows:

ws.on('connection', function(client){
console.log(' Client.on('join', function(msg){
             // Check if there are duplicates
           if(checkNickname(msg)){
                client.emit('nickname', 'The nickname is duplicated!');
         }else{
Client.nickname = msg;
                 ws.sockets.emit('announcement', 'System', msg 'Joined the chat room!');
}
});
// Listen to send messages
Client.on('send.message', function(msg){
Client.broadcast.emit('send.message',client.nickname, msg);
});
// Notify other users when disconnecting
Client.on('disconnect', function(){
If(client.nickname){
Client.broadcast.emit('send.message','System', client.nickname 'Leave the chat room!');
}
})
})


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

Copy code The code is as follows:
// Check if 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

Since the server uses a third-party websokcet framework, the front-end page needs to reference the socket.io client code separately. The source file can be found in the socket.io module. The path under Windows is node_modulessocket.ionode_modulessocket.io-clientdist. Here is For development and compressed versions, just quote the development version by default.

The front end mainly handles input nickname checking and message processing. The complete code is as follows:

Copy code The code is as follows:




    socket.io 聊天室例子
   
   
   
   


   

        

            

                

        

        

            
            
            
        

   





这里提供完整的代码压缩文件

总结

nodejs是一个好东西,尤其是在处理消息通讯,网络编程方面,天生的异步IO.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template