Node实现websocket聊天室

const express = require('express');
const app = express();
const ws = require('ws').Server;
const wss = new ws({port: 3001});
var sockets = [];

wss.on('connection', function(ws) {
    ws.send('连接成功');
    sockets.push(ws);

    ws.on('message', function(data) {
        ws.send(data);

        try {
            sockets.forEach(function (socket) {
                 if (ws != socket) {
                    socket.send(data);
                 }
            });
        } catch (err) {
            console.log(err);
        }
    });

    ws.on('error', function(e) {
        console.log(e);
    });
    ws.on('close', function(e) {
        console.log(e);
    });
});

app.use(express.static(__dirname)).listen(3000, 'localhost');
app.get('/', (req, res) => {
    res.sendFile(__dirname+'/websocket.html');
});

  

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>websocket</title>
    <link rel="stylesheet" href="test.css">
</head>
<body>
<input id="msg" type="text"/>
<button id="send" onclick="sendMsg()">发送</button>
<script>
    var ws = new WebSocket('ws://localhost:3001');
    ws.onopen = function(e) {
        console.log(e);
    };

    ws.onmessage = function(data) {
        console.log(data.data);
        showMsg(data.data);
    };

    ws.onerror = function(e) {
        console.log(e);
    };
    ws.onclose = function(e) {
        console.log(e);
    };


    function sendMsg() {
        var msg = document.getElementById('msg').value;
        var now = (new Date()).toLocaleTimeString();
        ws.send(now+'@'+msg);
    }

    function showMsg(data) {
        var msg = document.createElement('div');
        msg.innerHTML = data;
        document.body.appendChild(msg);
    }

    document.onkeyup = function(event) {
        event = event || window.event;
        if (event.keyCode == 13) {
            sendMsg();
        }
    };
</script>
</body>
</html>

  

posted @ 2018-02-05 16:14  鱿鱼须须  阅读(249)  评论(0编辑  收藏  举报