Html Websocket
用来测试Websocket的时候,写了一个测试的Html demo
可以发送文本,文件(这里用的是图片文件,input 选择图片,然后回显,再将其转为Base64,然后传递一个json的字符串)
<!DOCTYPE html> <title>WebSocket</title> <h2>HTML Websocket Client</h2> <body> <button onclick="connectSocketFun()">连接websocket</button><br><br> <button onclick="disconnectSocketFun()">断开连接</button><br><br> <input type="text" name="firstname" value="发送的数据"> <br><br> <button onclick="sendTextFun()">发送文本</button><br><br> <div> <span> <span></span> <input type="file" onchange="handleFiles(this.files)"> </span> </div> <div class="addBorder" id="imgDiv"> <img id="imgContent" style="height: 300px;width: 300px;"> </div><br> <button onclick="sendFileFun()">发送文件</button><br><br> <div id="output"></div> </body> <script> var ws = null; var base64 = ''; function handleFiles(files) { if (files.length) { let file = files[0]; let reader = new FileReader(); reader.onload = function () { var decu = document.getElementById('imgContent'); decu.src = this.result; base64 = this.result; }; reader.readAsDataURL(file); } } function connectSocketFun() { alert("连接websocket"); ws = new WebSocket("ws://localhost:8080/hello"); console.log(ws.readyState); ws.onopen = function (e) { log("Connected"); } ws.onclose = function (e) { log("Disconnected: " + e.reason); } ws.onerror = function (e) { log("Error "); } ws.onmessage = function (e) { log("Message received: " + e.data); } console.log(ws.readyState); } function disconnectSocketFun() { ws.close(); alert("断开连接websocket"); } function sendTextFun() { ws.send("发送文本"); alert("发送文本"); } function sendFileFun() { var data = { name: 'test文件名', base64: base64 } var dataJson = JSON.stringify(data); ws.send(dataJson); alert("发送文件"); } function log(s) { var p = document.createElement("p"); p.style.wordWrap = "break-word"; p.textContent = s; output.appendChild(p); } </script> </html>