DBMNG数据库管理与应用

才能是来自独创性。独创性是思维、观察、理解和判断的一种独特的方式。
当前位置:首页 > 经验分享 > Javascript

nodeJS实现的简单聊天室功能示例

app.js:

// 引入express模块
var express = require('express');
// 创建Web服务器对象
var app = express();
let chatMsgs = [];
// 静态资源处理
app.use(express.static('public'));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.listen(3000, () => console.log('服务器启动成功'));

app.get('/getMsg', function (req, res) {
    res.send(chatMsgs);
});

app.post('/sendMsg', function (req, res) {
    console.log(req.body);
    chatMsgs.push({ name: req.body.name, content: req.body.content });
});

app.post('/clearMsg', function (req, res) {
    console.log(req.body);
    if (req.body.cmd == 'clear') {
        chatMsgs = [];//清屏
    }
    res.send('ok');
});

Ajax聊天室示例-后台清屏功能:clear.html:

            Ajax聊天室示例-后台        清屏

前台聊天界面index.html:

            Ajax聊天室示例        欢迎访问Ajax聊天室示例                            发送        ' + new Date().toLocaleString() + " " + data[i].name + ':' + data[i].content + '';
            //         }
            //         document.getElementById('chat').innerHTML = html;
            //     }
            // }
            xhr.onload = function () {
                var data = JSON.parse(xhr.responseText);
                if (data.length !== tmpMsg.length) {
                    tmpMsg = data;
                    var html = '';
                    for (var i = 0; i ' + new Date().toLocaleString() + " " + data[i].name + '说:' + data[i].content + '';
                    }
                    document.getElementById('chat').innerHTML = html;
                }
            }
            xhr.send();
            //console.log('getMsg');
        }, 1000);
    " _ue_custom_node_="true">


完整代码 chatroomEZ.7z


本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2025 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号