Vue项目使用sockjs、Stomp连接WebSocket

----
git地址:
  前端vue:https://gitee.com/lddjava/vue-socket-demo.git
  后端服务:https://gitee.com/lddjava/vue-service-websocket.git




前端步骤:
   npm install sockjs-client
   npm install stompj


   import SockJS from "sockjs-client";
   import Stomp from "stompjs";



代码:
 <style scoped>
.webSocket {
  width: 100%;
  height: 100vh;
  /* background: red; */
}

.webSocket_title {
  width: 100%;
  height: 10vh;
  /* background: green; */
  font-size: 5vh;
  text-align: center;
  font-weight: bold;
  line-height: 10vh;
  color: #303133;
}

.webSocket_content {
  width: 100%;
  height: 89vh;
  border-top: 1vh solid #ebeef5;
  /* background: salmon; */
}

.webSocket_notice {
  width: 69%;
  height: 89vh;
  float: left;
  /* background: darkblue; */
  border-right: 1vh solid #ebeef5;
}

.webSocket_notice_title {
  width: 100%;
  height: 5vh;
  /* background: darkgreen; */
  text-align: center;
  font-size: 2.5vh;
  line-height: 5vh;
  color: #409eff;
  font-weight: bold;
}

.webSocket_notice_announcement {
  width: 100%;
  height: 84vh;
  /* background: salmon; */
  overflow: auto;
}

.webSocket_notice_announcement_item {
  width: 99%;
  margin: 0 auto;
  height: auto;
  border: 1px solid #e4e7ed;
  border-radius: 5px;
  margin-top: 1vh;
  font-size: 0.6vw;
  font-weight: bold;
}

.webSocket_chat {
  width: 30%;
  height: 89vh;
  float: right;
  /* background: darkcyan; */
}

.webSocket_chat_top {
  width: 100%;
  height: 40vh;
  /* background: red; */
}

.webSocket_chat_top_input {
  width: 100%;
  height: 4vh;
  /* background: green; */
}

.webSocket_chat_top_textarea {
  width: 100%;
  height: 35vh;
  /* background: darkseagreen; */
}

.webSocket_chat_bottom {
  width: 100%;
  height: 49vh;
  /* background: sandybrown; */
  overflow: auto;
}
.webSocket_chat_bottom_item {
  width: 99%;
  margin: 0 auto;
  height: auto;
  border-bottom: 1px solid #e4e7ed;
  margin-top: 1vh;
  font-size: 0.6vw;
  font-weight: bold;
}
</style>
<template>
  <div class="webSocket">
    <div class="webSocket_title">
      2020 Happy New Year's Day
    </div>
    <div class="webSocket_content">
      <div class="webSocket_notice">
        <div class="webSocket_notice_title">
          系统信息监控Notice
        </div>
        <div class="webSocket_notice_announcement">
          <div
            class="webSocket_notice_announcement_item"
            v-for="(item, index) in arrys"
            :key="index"
          >
            系统名称:{{ item.OsName }} --- cpu负载:{{ item.CpuLoad }} ---
            jvm线程负载:{{ item.ProcessCpuLoad }} --- 物理总内存:{{
              item.TotalMemorySize
            }}
            --- 已使用的物理内存:{{ item.UsedMemory }} --- 剩余物理内存:{{
              item.FreePhysicalMemorySize
            }}
            --- 时间:{{ item.Time }}
          </div>
        </div>
      </div>
      <div class="webSocket_chat">
        <div class="webSocket_chat_top">
          <div class="webSocket_chat_top_input">
            <input type="text" v-model="fromName" placeholder="发送方姓名" />
            <input type="text" v-model="toName" placeholder="接收方姓名" />
            <button :disabled="oneD" @click="onChatConnect">连接</button>
            <button :disabled="twoD" @click="onDisconConnect">断开连接</button>
          </div>
          <div v-show="textareaS" class="webSocket_chat_top_textarea">
            <textarea rows="15" cols="60" v-model="message" />
            <button @click="onSendMessage">发送消息</button>
          </div>
        </div>
        <div class="webSocket_chat_bottom">
          <div
            class="webSocket_chat_bottom_item"
            v-for="(item, index) in chatArray"
            :key="index"
          >
            发送方:{{ item.fromName }} 内容: {{ item.content }} 时间:{{
              item.time
            }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import SockJS from "sockjs-client";
import Stomp from "stompjs";
export default {
  name: "webSocket",
  data() {
    return {
      arrys: [],
      chatArray: [],
      stompClient: "",
      timer: "",
      fromName: "",
      toName: "",
      message: "",
      oneD: false,
      twoD: true,
      textareaS: false
    };
  },
  created() {},
  mounted() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      this.connection();
      let that = this;
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          that.stompClient.send("test");
        } catch (err) {
          console.log("断线了: " + err);
          that.connection();
        }
      }, 5000);
    },

    /**
     * 连接后台ws
     */
    connection() {
      var _this = this;
      // 建立连接对象
      let socket = new SockJS("http://localhost:9191/ws-vue");
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(socket);
      // 定义客户端的认证信息,按需求配置
      let headers = {
        Authorization: ""
      };
      // 向服务器发起websocket连接
      this.stompClient.connect(
        headers,
        function(res) {
          //连接成功 订阅系统信息主题消息
          _this.stompClient.subscribe("/topic/SystemInfo", function(msg) {
            _this.arrys.unshift(JSON.parse(msg.body));
          });
        },
        function(error) {
          // 连接发生错误时的处理函数
          console.log("失败");
          console.log(error);
        }
      );
    },

    /**
     * 断开连接
     *
     */
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect();
      }
    },
    /**
     * chat 连接
     */
    onChatConnect() {
      var _this = this;
      if (this.fromName == "" || this.toName == "") {
        alert("发送或接收方姓名不能为空");
        return;
      }

      if (this.stompClient != null && this.stompClient != "") {
        _this.oneD = true;
        _this.twoD = false;
        _this.textareaS = true;
        _this.stompClient.subscribe("/chat/" + _this.fromName, function(msg) {
          _this.chatArray.unshift(JSON.parse(msg.body));
        });
      } else {
        let socket = new SockJS("http://localhost:9191/ws-vue");
        this.stompClient = Stomp.over(socket);
        let headers = {
          Authorization: ""
        };
        // 向服务器发起websocket连接
        this.stompClient.connect(
          headers,
          function(res) {
            _this.oneD = true;
            _this.twoD = false;
            _this.textareaS = true;
            _this.stompClient.subscribe("/chat/" + _this.toName, function(msg) {
              _this.chatArray.unshift(JSON.parse(msg.body));
            });
          },
          function(error) {
            console.log("失败");
            console.log(error);
          }
        );
      }
    },

    /**
     * chat 伪断开连接
     */
    onDisconConnect() {
      this.fromName = "";
      this.toName = "";
      this.oneD = false;
      this.twoD = true;
      this.textareaS = false;
    },

    /**
     * 发送消息
     */
    onSendMessage() {
      var obj = {
        fromName: this.fromName,
        toName: this.toName,
        content: this.message
      };
      this.stompClient.send("/app/chat/message", {}, JSON.stringify(obj));
      this.message = "";
    }
  }
};
</script>
 

 

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Vue 3中使用stomp-websocket,你可以按照以下步骤进行操作: 1. 首先,你需要安装stompjs和sockjs-client依赖。在你的Vue项目根目录下,打开终端并运行以下命令: ```shell npm install stompjs sockjs-client --save ``` 2. 在你需要使用stomp-websocket的组件中,引入stompjs和sockjs-client库。你可以在Vue组件的`<script>`标签中添加以下代码: ```javascript import { Stomp } from 'stompjs'; import SockJS from 'sockjs-client'; ``` 3. 接下来,你可以在组件的方法中创建和管理stomp客户端连接。例如,在`created`钩子函数中,可以添加以下代码: ```javascript created() { const socket = new SockJS('http://localhost:8080/your-websocket-endpoint'); // 替换为你的WebSocket端点URL this.stompClient = Stomp.over(socket); this.stompClient.connect({}, this.onConnect, this.onError); }, methods: { onConnect() { // 连接成功后的处理逻辑 }, onError(error) { // 连接失败后的处理逻辑 } } ``` 4. 在`onConnect`方法中,你可以订阅并接收消息。例如: ```javascript onConnect() { this.stompClient.subscribe('/your-destination', (message) => { // 处理收到的消息 console.log(message.body); }); } ``` 这里的`/your-destination`是你想要订阅的目标地址。 5. 最后,当你不再需要连接时,记得在适当的时候断开连接: ```javascript beforeDestroy() { this.stompClient.disconnect(); } ``` 这样,你就可以在Vue 3中使用stomp-websocket了。请注意,上述代码中的URL和订阅目标地址需要根据你的实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值