当前位置:主页 > 脚本语言 > NodeJS >

Node.js用Socket.IO做聊天软件的实现示例

时间:2022-11-17 10:15:14 | 栏目:NodeJS | 点击:

效果

index.html文件

该页面主要是渲染聊天界面

<!DOCTYPE html>
<html>
<head>
    <title>Socket.IO chat</title>
    <style>
        body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

        #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
        #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
        #input:focus { outline: none; }
        #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages > li { padding: 0.5rem 1rem; }
        #messages > li:nth-child(odd) { background: #efefef; }
        .message{font-size: 40px;color: skyblue}
        .name{font-size: 15px;color: pink}
    </style>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
    <input id="input" autocomplete="off" name="main" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
    let name=prompt("输入用户名");
    //拿到用户名后进行非空验证
    if(name == '' || name == null){
        alert("先输入用户名")
    }else {
    	//初始化socket模块
        var socket = io();
        socket.emit('name message',name);//向服务器发送消息(用户名信息)
        let form = document.getElementById('form');
        let inputMain = document.querySelector('input[name="main"]');
        form.addEventListener('submit', function(e) {
            e.preventDefault();//取消默认提交事件
            if (inputMain.value) {//如果文本框中有消息
                socket.emit('chat message', inputMain.value);//向服务器发送消息(聊天信息)
                inputMain.value = '';
            }

        });
        //渲染服务器端发送的用户名信息(不仅是自己的,还有别的用户的)
        socket.on('name message',function (msg){
            var item = document.createElement('li');
            item.classList.add("name")
            item.textContent = msg;
            messages.appendChild(item);
        })
        //渲染服务器端发送的聊天信息(不仅是自己的,还有别的用户的)
        socket.on('chat message', function(msg) {
            var item = document.createElement('li');
            item.classList.add("message")
            item.textContent = msg;
            messages.appendChild(item);
            window.scrollTo(0, document.body.scrollHeight);
        });
    }
</script>
</body>
</html>

index.js

该文件主要用于聊天信息后端处理

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
//引入socket.io
const {Server}=require('socket.io')
const io=new Server(server)

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});
io.on('connection',(socket)=>{
    let name;
    socket.on('name message', (msg) => {
       name=msg;
       io.emit('name message', name+"已上线");
        socket.on("disconnect", (reason) => {
            io.emit('name message', name+"已断开");
        });
    });

    socket.on('chat message', (msg) => {
        io.emit('name message', name);
        io.emit('chat message', msg);
    });

})
server.listen(3000, () => {
    console.log('listening on *:3000');
});

实现方法

您可能感兴趣的文章:

相关文章