运行截图如下:
输入数据点击发送:
源码如下:
- <!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
是网上随意找的。