【nodeJS】实现简易聊天室

html页面

chat.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>ChatRoom</h1>
    <div id="chatroom" style="width:400px;overflow:auto;border:1px solid blue">
    </div>

    <input type="text" name="sayinput" id="sayinput" value="">

    <input type="button" name="send" id="sendbutton" value="发送">
</body>
<script src="./js/client.js"></script>
<script>
    sendbutton.onclick = function () {
        ws.send(sayinput.value)
        sayinput.value = ''
    }
</script>
</html>

服务器端(node)

server.js
//使用时将IP和端口号修改即可,由于本聊天室使用node.js,所以在运行时需要用node server启动服务器
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 9000 });

let clients = [];

wss.on('connection', function (ws) {
    // console.log(getClientIP(ws))
    ws.name = clients.length + 1
    clients.push(ws)


    ws.on('message', function (message) {
        clients.forEach(item => {
            item.send(ws.name + "说:" + message)
        })
    })
    ws.on('close',function(){
        console.log(ws.name+"离开")
    })
})
let port = 9000
console.log("server run in " + port)
client.js
var ws = new WebSocket('ws://127.0.0.1:9000/')

ws.onopen = function () {
    ws.send("你好")
}
ws.onmessage = function (event) {
    var charoot = document.getElementById('chatroom')
    chatroom.innerHTML += '<br>' + event.data
}
ws.onclose = function () {
    console.log('Closed')
}
ws.onerror = function (err) {
    alert('Error:' + err)
}

版权声明:本文为weixin_53126517原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。