Node.js笔记-使用socket.io构建websocket聊天室

x33g5p2x  于2021-11-16 转载在 其他  
字(1.7k)|赞(0)|评价(0)|浏览(448)

先安装socket.io

npm install socket.io

服务端代码:

let app = require('http').createServer();
let io = require('socket.io')(app, { cors: true });

let port = 3000;
let clientCount = 0;

app.listen(port);

io.on('connection', function (socket) {

    clientCount++;
    socket.nickname = 'user' + clientCount;
    io.emit('enter', socket.nickname + ' comes in');

    socket.on('message', function (str) {

        io.emit('message', socket.nickname + ' says: ' + str);
    })

    socket.on('disconnect', function () {

        io.emit('leave', socket.nickname + ' left');
    })
});


console.log("Websocket server listening on port = " + port)

客户端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocketIO</title>
    <script src="https://cdn.socket.io/4.0.1/socket.io.js"></script>
</head>
<body>
    <h1>Chat Room</h1>
    <input id="sendTxt" type="text" />
    <button id="sendBtn">发送</button>
    <script type="text/javascript">
        let socket = io("ws://localhost:3000/");
        function showMessage(str, type){

            let div = document.createElement('div');
            div.innerHTML = str;
            if(type == "enter"){

                div.style.color = "blue";
            }
            else if(type == "leave"){

                div.style.color = "red";
            }
            document.body.appendChild(div);
        }

        document.getElementById("sendBtn").onclick = function () {

            let txt = document.getElementById("sendTxt").value;
            if(txt){
                console.log(txt)
                socket.emit('message', txt);
            }
        }

        socket.on('enter', function (data) {

            showMessage(data, 'enter');
        })

        socket.on('message', function (data) {

            showMessage(data, 'message');
        })

        socket.on('leave', function (data) {

            showMessage(data, 'leave');
        })

    </script>
</body>
</html>

运行截图如下:

退出:

相关文章