<!DOCTYPE html> <htmllang="en"> <head> <metacharset="UTF-8"> <title>Title</title> </head> <body> <divid="msg"></div> <inputtype="text"id="text"> <inputtype="submit"value="发送数据"onclick="song()"> </body> <script> var msg = document.getElementById("msg"); var wsServer = 'ws://0.0.0.0:9502'; //调用websocket对象建立连接: //参数:ws/wss(加密)://ip:port (字符串) var websocket = new WebSocket(wsServer); //onopen监听连接打开 websocket.onopen = function(evt){ //websocket.readyState 属性: /* CONNECTING 0 The connection is not yet open. OPEN 1 The connection is open and ready to communicate. CLOSING 2 The connection isin the process of closing. CLOSED 3 The connection is closed or couldn't be opened. */ msg.innerHTML = websocket.readyState; };
functionsong(){ var text = document.getElementById('text').value; document.getElementById('text').value = ''; //向服务器发送数据 websocket.send(text); } //监听连接关闭 // websocket.onclose = function (evt) { // console.log("Disconnected"); // };