目录结构
首先新建文件夹,然后确保电脑上有nodejs,然后在文件夹目录运行 npm i node-websocket
使用如下代码:
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
/* div {
height: 200px;
width: 200px;
border: 1px solid black;
} */
</style>
</head>
<body>
<input type="text" placeholder="输入信息"><button>发送</button>
<div></div>
<script>
let div = document.querySelector('div');
let input = document.querySelector('input');
let button = document.querySelector('button');
var socket = new WebSocket('ws://localhost:3000')
// 连接触发
socket.addEventListener('open', function () {
div.innerHTML = '连接聊天室成功了'
})
// 发送消息
button.addEventListener('click', function() {
var value = input.value
input.value = ''
socket.send(value)
})
// 接收信息
socket.addEventListener('message', function(e) {
var dv = document.createElement('div')
dv.innerHTML = e.data
div.appendChild(dv)
})
</script>
</body>
</html>
serve.js
const ws = require("nodejs-websocket");
let count = 0;
const serve = ws.createServer(conn => {
console.log('新的连接');
count++
conn.userName = `用户${count}号`
broadcast(`${conn.userName}进入了聊天室`);
// 接收到了浏览器的数据
conn.on('text', data => {
broadcast(`${conn.userName}:` + data)
})
// 关闭的时候触发
conn.on('close', data => {
console.log('关闭连接');
broadcast(`${conn.userName}离开了聊天室`);
})
// 发生异常 触发
conn.on('error', data => {
console.log('发生异常');
})
})
// 广播信息给所有的用户
function broadcast(msg) {
serve.connections.forEach(item => {
item.send(msg)
})
}
serve.listen(3000, () => {
console.log('监听端口3000')
})
然后在终端运行
然后打开index.html 文件即可