12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- <!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>Test Websocket</title>
- </head>
- <body>
- <input type="text" id="message">
- <button id="submit">提交</button>
- <script>
- // 创建 websocket 实例
- let websocket = new WebSocket("ws://192.168.51.100:8888");
- // 处理连接打开的回调函数
- websocket.onopen = function() {
- console.log("连接建立");
- }
- // 处理收到消息的回调函数
- // 控制台打印消息
- websocket.onmessage = function(e) {
- console.log("收到消息: " + e.data);
- }
- // 处理连接异常的回调函数
- websocket.onerror = function() {
- console.log("连接异常");
- }
- // 处理连接关闭的回调函数
- websocket.onclose = function() {
- console.log("连接关闭");
- }
- // 实现点击按钮后, 通过 websocket 发送请求
- let input = document.querySelector('#message');
- let button = document.querySelector('#submit');
- button.onclick = function() {
- console.log("发送消息: " + input.value);
- websocket.send(input.value);
- }
- </script>
- </body>
- </html>
|