运行截图如下:
输入数据点击发送:
源码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<h1>Echo Test</h1>
<input id="sendTxt" type="text" />
<button id="sendBtn">发送</button>
<div id="recv"></div>
<script type="text/javascript">
let websocket = new WebSocket("ws://82.157.123.54:9010/ajaxchattest");
websocket.onopen = function () {
console.log('websocket open');
document.getElementById("recv").innerText = "Connected";
}
websocket.onclose = function () {
console.log('websocket close');
}
websocket.onmessage = function (ev) {
console.log(ev.data);
document.getElementById("recv").innerHTML = ev.data;
}
document.getElementById("sendBtn").onclick = function () {
let txt = document.getElementById("sendTxt").value;
console.log(txt);
websocket.send(txt);
}
</script>
</body>
</html>
这个地址:
ws://82.157.123.54:9010/ajaxchattest
是网上随意找的。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq78442761/article/details/121231480
内容来源于网络,如有侵权,请联系作者删除!