index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. }
  71. });
  72. function f0(i) {
  73. return (i < 10 ? '0' : '') + i
  74. }