模拟服务端
bash
var Websocket = require('websocket').server
var http = require('http')
var httpServer = http.createServer().listen(8080,function() {
console.log('http://127.0.0.1:8080')
})
var wsServer = new Websocket({
httpServer: httpServer,
autoAcceptConnections: false
})
// 保存客户端的connection状态
var conArr = []
// 生成事件:request:事件名称 request:请求过来的数据
wsServer.on('request', function (request) {
// 怎么拿到连接实例
var connection = request.accept();
conArr.push(connection) // 保持
connection.on('message', function (msg) {
console.log(msg);
for (let i = 0; i < conArr.length; i++) {
conArr[i].send(msg.utf8Data)
}
// connection.send(msg.utf8Data) //返回至客户端
})
})
模拟客户端
bash
<!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>
<div id="msg"></div>
<input type="text" id="text">
<input type="button" value="发生" onclick="send()">
<script>
// web客户端的链接
var websocket = new WebSocket('ws://127.0.0.1:8080')
console.log(websocket.readyState);
// readyState: 0:new 链接未建立,正在建立链接 1:链接建立成功 2:链接正在关闭 3:链接已经关闭
// ws / wss
// 链接建立是异步的
websocket.onopen = function(){ // 类似于ajax,需要处理请求状态
console.log(websocket.readyState);
}
function send() {
var text = document.getElementById('text').value
websocket.send(text)
}
// 客户端接收服务器传过来的数据
// 绑定一个服务器推送事件
websocket.onmessage = function(back) {
console.log(back.data);
}
</script>
</body>
</html>