var DemoHandler = function () { function keyPath(url, name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //如果地址栏中出现中文则进行编码 var r = encodeURI(url).substr(1).match(reg); if (r != null) { //将中文编码的字符重新变成中文 return decodeURI(unescape(r[2])); } } this.onopen = function (event, ws) { // ws.send('hello 连上了哦') var path = keyPath(ws.url, "path"); document.getElementById(path).innerHTML += '
hello 连上了哦[' + path + ']

'; } /** * 收到服务器发来的消息 * @param {*} event * @param {*} ws */ this.onmessage = function (event, ws) { var data = event.data; var path = keyPath(ws.url, "path"); document.getElementById(path).innerHTML += '
' + data + '

' } this.onclose = function (e, ws) { // error(e, ws) } this.onerror = function (e, ws) { // error(e, ws) } /** * 发送心跳,本框架会自动定时调用该方法,请在该方法中发送心跳 * @param {*} ws */ this.ping = function (ws) { console.log("发心跳了") // var typedArray = new Uint8Array(4); var path = keyPath(ws.url, "path"); var buff = new TextEncoder().encode(path); // console.log(buff) // console.log(stringToByte(path)) ws.send(buff) } function stringToByte(str) { var bytes = new Array(); var len, c; len = str.length; for (var i = 0; i < len; i++) { c = str.charCodeAt(i); if (c >= 0x010000 && c <= 0x10FFFF) { bytes.push(((c >> 18) & 0x07) | 0xF0); bytes.push(((c >> 12) & 0x3F) | 0x80); bytes.push(((c >> 6) & 0x3F) | 0x80); bytes.push((c & 0x3F) | 0x80); } else if (c >= 0x000800 && c <= 0x00FFFF) { bytes.push(((c >> 12) & 0x0F) | 0xE0); bytes.push(((c >> 6) & 0x3F) | 0x80); bytes.push((c & 0x3F) | 0x80); } else if (c >= 0x000080 && c <= 0x0007FF) { bytes.push(((c >> 6) & 0x1F) | 0xC0); bytes.push((c & 0x3F) | 0x80); } else { bytes.push(c & 0xFF); } } return bytes; } }