-
注意:
webscoket.onopen这个事件在new WebSocket("ws://localhost:9998")的时候如果readyStatus 是 1 他会自动调用,因此如果你在new的时候,没有声明onopen,那么就不会调用了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<button id="connection">连接</button>
<button id="send" disabled>发送</button>
<h1 id="label"></h1>
</div>
<script>
let connection = document.querySelector("#connection");
let send = document.querySelector("#send");
let label = document.querySelector("#label");
let webscoket = null;
webscoket = new WebSocket("ws://localhost:9998");
connection.onclick = function () {
console.log(webscoket)
webscoket.onopen = (a) => {
console.log("连接成功");
send.disabled = false;
};
webscoket.onclose = (a) => {
// console.log(a);onopen
console.log("连接失败");
send.disabled = true;
};
webscoket.onmessage = (msg) => {
label.innerHTML = msg.data
}
};
send.onclick = function() {
webscoket.send(1111)
}
</script>
</body>
</html>
image.png
网友评论