DemoHandler.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. var DemoHandler = function () {
  2. function keyPath(url, name) {
  3. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  4. //如果地址栏中出现中文则进行编码
  5. var r = encodeURI(url).substr(1).match(reg);
  6. if (r != null) {
  7. //将中文编码的字符重新变成中文
  8. return decodeURI(unescape(r[2]));
  9. }
  10. }
  11. this.onopen = function (event, ws) {
  12. // ws.send('hello 连上了哦')
  13. var path = keyPath(ws.url, "path");
  14. document.getElementById(path).innerHTML += '<blockquote class="layui-elem-quote layui-quote-nm">hello 连上了哦[' + path + ']</blockquote><br>';
  15. }
  16. /**
  17. * 收到服务器发来的消息
  18. * @param {*} event
  19. * @param {*} ws
  20. */
  21. this.onmessage = function (event, ws) {
  22. var data = event.data;
  23. var path = keyPath(ws.url, "path");
  24. document.getElementById(path).innerHTML += '<blockquote class="layui-elem-quote layui-quote-nm">' + data + '</blockquote><br>'
  25. }
  26. this.onclose = function (e, ws) {
  27. // error(e, ws)
  28. }
  29. this.onerror = function (e, ws) {
  30. // error(e, ws)
  31. }
  32. /**
  33. * 发送心跳,本框架会自动定时调用该方法,请在该方法中发送心跳
  34. * @param {*} ws
  35. */
  36. this.ping = function (ws) {
  37. console.log("发心跳了")
  38. // var typedArray = new Uint8Array(4);
  39. var path = keyPath(ws.url, "path");
  40. var buff = new TextEncoder().encode(path);
  41. // console.log(buff)
  42. // console.log(stringToByte(path))
  43. ws.send(buff)
  44. }
  45. function stringToByte(str) {
  46. var bytes = new Array();
  47. var len, c;
  48. len = str.length;
  49. for (var i = 0; i < len; i++) {
  50. c = str.charCodeAt(i);
  51. if (c >= 0x010000 && c <= 0x10FFFF) {
  52. bytes.push(((c >> 18) & 0x07) | 0xF0);
  53. bytes.push(((c >> 12) & 0x3F) | 0x80);
  54. bytes.push(((c >> 6) & 0x3F) | 0x80);
  55. bytes.push((c & 0x3F) | 0x80);
  56. } else if (c >= 0x000800 && c <= 0x00FFFF) {
  57. bytes.push(((c >> 12) & 0x0F) | 0xE0);
  58. bytes.push(((c >> 6) & 0x3F) | 0x80);
  59. bytes.push((c & 0x3F) | 0x80);
  60. } else if (c >= 0x000080 && c <= 0x0007FF) {
  61. bytes.push(((c >> 6) & 0x1F) | 0xC0);
  62. bytes.push((c & 0x3F) | 0x80);
  63. } else {
  64. bytes.push(c & 0xFF);
  65. }
  66. }
  67. return bytes;
  68. }
  69. }