index.js // 这里是nodejs。启动服务器
let WebSocket = require('websocket').server // 引入websocket的服务
let http = require('http') // 创建http 因为websocket基于http协议握手
let httpServer = http.createServer().listen(8080, function () {
console.log('http://127.0.0.1:8080') //
})
let wsServer = new WebSocket({
httpServer,
autoAcceptConnections: false, //
})
const connects = [] // 创建链接数组,后期作为连接池
wsServer.on('request', function (req) {
let connect = req.accept()
connects.push(connect)
connect.on('message', function (msg) {
console.log(msg)
connects.forEach(item => {
item.send(msg.utf8Data)
})
// connect.send(msg.utf8Data)
})
})
这里是 index.html // 执行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>
<input type="text" />
<button onclick="send()">按钮</button>
</body>
<script>
let webSocket = new WebSocket('ws://127.0.0.1:8080') // new一个websocket对象
webSocket.onopen = () => {
// 开启websocket
console.log(webSocket.readyState) // 打印出websocket的状态
}
function send(msg) {
// button事件
let val = document.querySelector('input').value
webSocket.send(val) // websocket 向服务端发送信息
}
webSocket.onmessage = back => {
// 监听返回的信息
console.log(back) // websocket打印出返回的信息
}
</script>
</html>