index.js 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * WebSocket测试
  3. */
  4. new Vue({
  5. el: '#pageContainer',
  6. data: {
  7. url: 'ws://121.40.165.18:8800',
  8. msg: '',
  9. connBtn: false,
  10. closeBtn: true,
  11. results: [],
  12. websock: null,
  13. },
  14. watch: {},
  15. mounted: function () {
  16. this.$refs.url.focus();
  17. },
  18. destroyed() {
  19. this.websock.close() //离开之后断开websocket连接
  20. },
  21. methods: {
  22. initWebSocket() { //初始化weosocket
  23. this.results.push(this.now() + "连接到:" + this.url);
  24. console.log(this.now() + "连接到:" + this.url)
  25. this.websock = new WebSocket(this.url);
  26. this.websock.onmessage = this.websocketOnMessage;
  27. this.websock.onopen = this.websocketOnOpen;
  28. this.websock.onerror = this.websocketOnError;
  29. this.websock.onclose = this.websocketOnClose;
  30. },
  31. websocketSend() {//数据发送
  32. this.websock.send(this.msg);
  33. this.results.push(this.now() + "发送:" + this.msg);
  34. console.log(this.now() + "发送:" + this.msg)
  35. this.msg = '';
  36. },
  37. websocketClose() {//数据发送
  38. this.results.push(this.now() + "关闭连接");
  39. console.log(this.now() + "关闭连接")
  40. this.websock.close();
  41. },
  42. cleanupMsg() {
  43. this.results = [];
  44. },
  45. websocketOnOpen(e) { //连接建立之后执行send方法发送数据
  46. this.results.push(this.now() + "连接成功");
  47. console.log(this.now() + "连接成功!", e)
  48. this.connBtn = true
  49. this.closeBtn = false
  50. },
  51. websocketOnError(e) {//连接建立失败重连
  52. this.results.push(this.now() + "连接失败,请检查连接地址是否正确或服务器是否正常");
  53. console.log(this.now() + "连接失败,请检查连接地址是否正确或服务器是否正常!", e)
  54. this.connBtn = false
  55. this.closeBtn = true
  56. },
  57. websocketOnMessage(msg) { //数据接收
  58. this.results.push(this.now() + "收到消息:" + msg.data);
  59. console.log(this.now() + "收到消息:", msg)
  60. },
  61. websocketOnClose(e) { //关闭
  62. console.log(this.now() + "连接断开!", e)
  63. this.connBtn = false
  64. this.closeBtn = true
  65. },
  66. now() {
  67. let date = new Date();
  68. return f0(date.getHours()) + ":" + f0(date.getMinutes()) + ":" + f0(date.getSeconds()) + " - ";
  69. },
  70. openDonateModal: function(event) {
  71. event.preventDefault();
  72. event.stopPropagation();
  73. chrome.runtime.sendMessage({
  74. type: 'fh-dynamic-any-thing',
  75. thing: 'open-donate-modal',
  76. params: { toolName: 'websocket' }
  77. });
  78. },
  79. openOptionsPage: function(event) {
  80. event.preventDefault();
  81. event.stopPropagation();
  82. chrome.runtime.openOptionsPage();
  83. }
  84. }
  85. });
  86. function f0(i) {
  87. return (i < 10 ? '0' : '') + i
  88. }