基于nodejs+webSocket的聊天室(实现:加入聊天室、退出聊天室、在线人数、在线列表、发送信息、接收信息)

1  安装 socket.io模块 npm install

"socket.io": "latest"

2 app.js相关

ws = require('socket.io'); //依赖该模块

let server = http.createServer(app).listen(300); //将服务器赋值给变量

let io = ws(server); 

io.on('connection', function (socket) { //服务器监听'connection'
    console.log(socket);
}

3 在创建 public/chat.html

<!--引入的原因:当websocket服务不能用时使用ajax轮查询继续通信-->
<script src="socket.io.min.js"></script>

<script>
        io.connect('/'); //客户端发起 connect连接
</script>

4 浏览器打开chat.html页面

说明websocket通信建立连接成功

6 开始(搞)做(事)聊天室

7 服务器端代码

let userList = {},
    usernum = 0;
io.on('connection', function (socket) {
    
    socket.on('msg', function (data) { //接收前端发送过来的聊天内容
        //console.log(data);
        //把有前台发来的内容广播出去
        io.emit('chat', data); 
    });
    socket.on('login', function (data) { //服务端监听消息名为login的通信 通过回调函数反应给浏览器
        userList[data.userid] = data.name; //给对象userList添加内容
        socket.name = data.name; //保留客户端发来的该用户username
        socket.userid = data.userid; //保留客户端发来的该用户的userid
        usernum++;//登录一个用户+1
        data.num = usernum; //给data添加一个num属性并赋值
        //console.log(usernum);
        io.emit('login',{data:data, userList:userList}); //把加入聊天室的人广播出去
    });
    // disconnect 退出触发的事件
    socket.on('disconnect', function(){
        delete userList[socket.userid];//删除退出的用户
        usernum--;
        console.log(usernum);
        io.emit('logout',{name:socket.name, num:usernum, userList:userList});
    });
})

8 前台页面代码  --使用jquery库

    用户名:<input type="text" class="name"> <button class="join" onclick="Chat.login()">进入聊天室</button>
    <div id="con"></div>
    <input type="text" class="send-con"><button onclick="Chat.submit()" class="send">发送</button>
    <div class="num"></div>
    <div class="userlist"></div>


    <!--引入的原因:当这个服务不能用时使用ajax轮查询继续通信-->
    <script src="socket.io.min.js"></script>
    <script>
        const Chat = {
            joinBtn: $('.join'),
            sendMsgBtn: $('.send'),
            usename: null,  //保存用户登录时输入的用户名
            userid: null,   //保存用户登录时候的id
            socket: null,   //保存 WebSocket服务
            init: function(username){  //初始化
                this.socket = io.connect('/'); //客户端发起 connect连接
                this.username = username; //给用户名赋值
                this.userId = new Date().getTime() +''+ Math.floor(Math.random()*899+100); 
                this.socket.emit('login', {name: this.username, userid:this.userId}); //向服务端提交名为'login'的信息 
                this.socket.on('login', function(data){ //监听名为'login'由服务端发来的信息
                    Chat.updateSystemMsg(data, 'login'); //?? Chat
                    //console.log(this);
                });
                //服务端发来'logout'退出信息时
                this.socket.on('logout', function(data){
                   Chat.updateSystemMsg(data, 'logout');
                });
                //服务端发来 chat的聊天消息
                this.socket.on('chat', function(data){
                    //console.log(data);
                    Chat.updateSystemMsg(data, 'chat');
                });
            },
            updateSystemMsg: function(data, action){
                let $con = $('#con'),
                    html = $con.html(),
                    $userList = $('.userlist'),
                    userList = '',
                    $num = $('.num'),
                    numList = $num.html();
                    //console.log(data);
                if(action === 'login'){ //当是登录时候
                    html += `<p>${data.data.name}进入了聊天室`;
                    numList = `当前在线人数${data.data.num}`;
                    $userList.empty();
                    for(let i in data.userList){
                        userList +=  `<p>${data.userList[i]}</p>`;
                    };
                    $userList.html('<h3>当前在线列表:</h3>'+userList);
                    $num.html(numList);
                }else if(action === 'logout'){ //当是退出的时候
                    //console.log(this.username);
                    html += `<p>${data.name}退出了聊天室`;
                    numList = `当前在线人数${data.num}`;
                    $userList.empty();
                    for(let i in data.userList){
                        userList +=  `<p>${data.userList[i]}</p>`;
                    };
                    $userList.html('<h3>当前在线列表:</h3>'+userList);
                    $num.html(numList);
                }else if(action === 'chat'){
                    html += `<p>${data.username}:${data.content}</p>`;
                }
                $con.html(html);
            },
            submit: function(){ //发送信息
                let $sendMsgInp = $('.send-con'),
                    sendCon = $sendMsgInp.val();
                if(sendCon){ //信息输入框输入的有内容
                    this.socket.emit('msg', {username:this.username, content:sendCon}); //发送 msg
                }else{
                    alert('发送的内容不能为空');
                }
            },
            login: function(){ //加入聊天室
                const $name = $('.name').val();
                $name && this.init($name); //$name不为空时 执行后面语句
            }
       
        }    
    </script>
原文地址:https://www.cnblogs.com/easyweb/p/6649321.html