vue实现websocket-client+websocket和后端通信(三)

11 篇文章 0 订阅

        在上一章中,我们介绍了使用@stomp/stompjs实现websocket和后端通信的方法。其实还有一种和@stomp/stompjs极其相似的实现,甚至我怀疑是不同版本而已。但是我不是专注于前端开发,只是因为测试需要所以研究了一下,这个技术就是websocket-client。

        经过测试发现websocket-client与@stomp/stompjs的实现几乎一模一样,只在建立连接时有区别。

        本片只是简单介绍其中不同之处,其他的实现,请参考:vue实现stompjs+websocket和后端(二)

使用websocket-client需要从新导入相关的组件。

​npm install webstomp-client

连接方式:

 // 创建SockJS对象
      this.socket = new WebSocket('ws://localhost:7000/websocket-demo/stmpwebsocket');
      // 创建Stomp客户端实例
      let stompClient = StompClient.over(this.socket);

      //请求头
      let headers = {
        'login': 'usename',
        'userId': this.userId
      }

      // 连接WebSocket
      stompClient.connect(headers, frame => {
        console.log('Connected: ' + frame);
        this.connected = true
      }, error => {
        console.error('STOMP error:', error);
      });

 还有就是发送,如果需要加入请求头的话。参数顺序有所变化:

stompClient.send(describetion, messagebODY, headers)

        其他的如订阅、关闭连接和@stomp/stompjs相似。这里就不说了,也没有详细测试,有问题请大家及时指出。

全部代码如下:

<template>
  <div class="f_c float_l">
    <div class="m_10 float_l">
      <el-input class='input_common' v-model="websocketPath" placeholder="后端websocket地址:http://ip:port/context/websocket-point" ></el-input>
      <el-input class='input_common' v-model="userId" placeholder="请输入用户名" ></el-input>
      <el-button v-if="!connected" @click=" connectWebsocket" >连接</el-button>
      <el-button v-else @click="disConnectWebsocket" >断开</el-button>
    </div>
    <el-divider />
    <div class="f_c" v-if="connected">
      <div>
        <el-input class='input_common' v-model="messageUrl" placeholder="请输入消息地址:/sendMessage"></el-input>
        <el-button @click="sendMessage" v-if="connected">发送</el-button>
      </div>
      <el-input class='input_common mt_10' v-model="message" type="textarea" :rows="2" placeholder="请输入需要发送的消息"></el-input>
    </div>
    <el-divider />
    <div class="f_c m_10 float_l" v-if="connected">
      <div class="float_l">
        <el-input class='input_common' v-model="subscribePath" placeholder="请输入监听地址:/subscribe/id"></el-input>
        <el-button @click="subscribeTopic" v-if="!subscribed">广播订阅</el-button>
        <el-button @click="unSubscribeTopic" v-else>取消订阅</el-button>
      </div>
      <div class="m_10 f_c">
        <span class="float_l">收到消息</span>
        <span style="border: aqua; width: 500px; height: 100px">{{receiveMessage}}</span>
      </div>
    </div>
      <div class="f_c m_10 float_l" v-if="connected">
        <div class="float_l">
          <el-input class='input_common' v-model="userSubscribePath" placeholder="请输入监听地址:/subscribe/id"></el-input>
          <el-button @click="subscribeUserTopic" v-if="!userSubscribed">用户订阅</el-button>
          <el-button @click="unUserSubscribeTopic" v-else>取消订阅</el-button>
        </div>
        <div class="m_10 f_c">
          <span class="float_l">收到消息</span>
          <span style="border: aqua; width: 500px; height: 100px">{{receiveUserMessage}}</span>
        </div>
    </div>

  </div>
</template>

<script>
import StompClient from 'webstomp-client';

export default {
  name: "index",
  data(){
    return {
      websocketPath:'localhost:7000/websocket-demo/stmpwebsocket',
      userId:'',
      subscribePath:'/topic/targetSubscribe',
      receiveMessage:'',
      userSubscribePath:'/user/queue/123456789',
      receiveUserMessage:'',
      messageUrl:'/message/stomp/sendMessage',
      message:'',
      connected: false,
      subscribed: false,
      userSubscribed:false,
      socket:null,
      stompClient:null,
      pushSubscriptionPromise: null,
      pushUserSubscriptionPromise: null
    }
  },
  methods:{
    connectWebsocket(){
      if(!this.websocketPath){
        this.$message.error("请先填写websocket地址信息")
        return
      }
      if(!this.userId){
        this.$message.error("请先填写用户信息")
        return
      }
      // 创建SockJS对象
      this.socket = new WebSocket('ws://' + this.websocketPath);
      // 创建Stomp客户端实例
      this.stompClient = StompClient.over(this.socket);

      //请求头
      let headers = {
        'login': 'usename',
        'userId': this.userId
      }

      // 连接WebSocket
      this.stompClient.connect(headers, frame => {
        console.log('Connected: ' + frame);
        this.connected = true
      }, error => {
        console.error('STOMP error:', error);
      });
    },
    sendMessage(){
      if(!this.message || !this.messageUrl){
        this.$message.error("请先填写websocket地址和消息内容信息")
        return
      }
      let msg = { message: this.message };
      console.log("数据发送:", this.messageUrl, msg)
      this.stompClient.send(this.messageUrl, JSON.stringify(msg), {});
    },
    onceSubscribe(){
      this.stompClient.subscribe('/message/subscribe/1232131321', function(message) {
        console.log('onceSubscribe-Message: ' + message.body);
      })
    },
    subscribeTopic(){
      if(!this.subscribePath){
        this.$message.error("请先填写订阅地址")
        return
      }
      // 订阅某个路径
      let number = 1
      this.subscribed = true
      //获取订阅结果用于取消订阅
      this.pushSubscriptionPromise = this.stompClient.subscribe(this.subscribePath, message => {
        // 处理接收到的消息
        console.log('收到消息', message);
        let nowMessage = '第' + number + '次收到订阅的消息:' + JSON.stringify(JSON.parse(message.body)) + '\r\n';
        this.receiveMessage += nowMessage;
        number ++;
      });
    },
    subscribeUserTopic(){
      if(!this.userSubscribePath){
        this.$message.error("请先填写用户的订阅地址")
        return
      }
      // 订阅某个路径
      let number = 1
      this.userSubscribed = true
      //获取订阅结果用于取消订阅
      this.pushUserSubscriptionPromise = this.stompClient.subscribe(this.userSubscribePath, message => {
        // 处理接收到的消息
        console.log('收到消息', message);
        let nowMessage = '第' + number + '次收到订阅的消息:' + JSON.stringify(JSON.parse(message.body)) + '\r\n';
        this.receiveUserMessage += nowMessage;
        number ++;
      });
    },
    unSubscribeTopic(){
      // 订阅某个路径
      this.pushSubscriptionPromise.unsubscribe();
      this.subscribed = false;
      this.receiveMessage = ''
    },
    unUserSubscribeTopic(){
      // 订阅某个路径
      this.pushUserSubscriptionPromise.unsubscribe();
      this.userSubscribed = false;
      this.receiveUserMessage = ''
    },
    disConnectWebsocket(){
      if (this.stompClient != null) {
        // 关闭连接
        this.stompClient.disconnect()
        this.stompClient = null
        this.socket.close()
        this.socket = null
        this.connected = false
        this.subscribed = false
        this.userSubscribed = false
        this.receiveMessage = ''
        this.receiveUserMessage = ''
      }
    },
    beforeDestroy(){
      if(this.stompClient != null){
        this.stompClient.disconnect()
        this.stompClient = null
        this.socket.close()
        this.socket = null
        this.connected = false
        this.subscribed = false
        this.userSubscribed = false
        this.receiveMessage = ''
        this.receiveUserMessage = ''
      }
    }
  }
}
</script>

<style scoped>

</style>
  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Vue前端框架)和Spring Boot(后端框架)结合起来实现websocket双工通信的步骤如下: 1. 首先,在Vue项目中安装`vue-native-websocket`插件。这个插件能够帮助我们在Vue中使用websocket。 2. 在Vue项目的根目录下创建一个文件,例如`webSocket.js`,在这个文件中,引入`vue-native-websocket`插件,并配置websocket服务的地址和端口号。 3. 在Vue项目的入口文件(例如`main.js`)中,引入`webSocket.js`文件,并将websocket插件注册到Vue实例中。 4. 在Vue组件中,使用`this.$socket`来访问websocket对象。可以使用`this.$socket.send()`方法发送消息给后端。 5. 在Spring Boot项目中,添加`spring-boot-starter-websocket`的依赖。 6. 创建一个继承自`WebSocketConfigurer`接口的类,并实现其中的`registerWebSocketHandlers`方法。在该方法中,注册一个`WebSocketHandler`来处理前端后端之间的websocket连接和消息传递逻辑。 7. 在`WebSocketHandler`中,重写`handleTextMessage`方法来处理接收到的文本消息。可以在这个方法中进行消息的处理逻辑,例如广播消息给所有连接的客户端。 8. 在Spring Boot的配置类(例如`Application.java`)中,添加`@EnableWebSocket`来启用websocket支持。 9. 启动Spring Boot项目,并运行Vue项目。此时,前端可以使用websocket连接后端,并进行双工通信前端可以通过`this.$socket.send()`方法发送消息给后端后端可以通过`WebSocketHandler`接收处理并响应消息给前端。 以上就是使用Vue和Spring Boot来实现websocket双工通信的基本步骤。通过这种方式,前端后端可以实时地进行双向通信,方便实现一些实时推送、聊天室等功能。 ### 回答2: Vue和Spring Boot结合实现WebSocket双工通信的步骤如下: 1. 在Vue项目中安装Vue-socket.io插件,可以在Vue项目的根目录下运行以下命令进行安装: ``` npm install --save vue-socket.io ``` 2. 在Vue项目的main.js文件中引入Vue-socket.io插件,并配置socket连接: ```javascript import VueSocketIO from 'vue-socket.io' import SocketIO from 'socket.io-client' Vue.use(new VueSocketIO({ debug: true, connection: SocketIO('http://localhost:8080'), // 这里的地址需要修改为后端的IP地址和端口号 })) ``` 3. 在Vue组件中使用WebSocket进行通信,例如,在Vue组件的created钩子中: ```javascript created() { this.$socket.emit('register', { userId: 123 }) // 发送注册消息给后端 this.$socket.on('message', (data) => { // 监听后端发送的消息 console.log('收到消息:', data) }) } ``` 4. 在Spring Boot中编写WebSocket后端控制器,处理前端发送的消息,并实现双工通信,例如: ```java @Controller public class WebSocketController { @Autowired private SimpMessagingTemplate messagingTemplate; @MessageMapping("/register") public void registerUser(@Payload Map<String, Long> payload) { // 处理注册逻辑,例如保存用户ID等 Long userId = payload.get("userId"); // 广播消息给所有连接的用户 messagingTemplate.convertAndSend("/topic/message", "用户 " + userId + " 加入了聊天室"); } // 其他接口处理逻辑... } ``` 5. 在Spring Boot中配置WebSocket相关的bean,例如,在配置类中添加以下配置: ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic"); // 消息代理前缀 registry.setApplicationDestinationPrefixes("/app"); // 应用消息前缀 } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS(); } } ``` 以上是Vue和Spring Boot实现WebSocket双工通信的基本步骤,当前端发送消息到后端时,后端可以处理并向所有连接的客户端发送广播消息,实现实时的双工通信。 ### 回答3: Vue和Spring Boot均提供了支持WebSocket的功能,通过结合Vue和Spring Boot,我们可以实现WebSocket双工通信。 首先,在Vue项目中使用Vue提供的WebSocket API建立与后端WebSocket连接,可以使用Vue的mounted生命周期钩子函数来实现这一步骤。通过WebSocket连接后,我们可以使用VueWebSocket对象来发送数据给后端,同时监听后端的数据。 在后端,我们使用Spring Boot提供的WebSocket支持来处理前端的请求。首先,在Spring Boot的配置文件中,我们需要开启WebSocket功能。然后,我们可以通过创建一个WebSocketHandler类来处理前端的请求和发送消息给前端。在WebSocketHandler中,我们可以实现OnOpen、OnMessage、OnClose等方法来处理前端连接、接收消息和关闭连接。在接收到消息后,我们可以编写相应的业务逻辑,如处理前端发送的数据,然后将处理结果发送给前端。 通过上述步骤,我们实现Vue和Spring Boot之间的WebSocket双工通信前端可以通过VueWebSocket对象与后端进行实时的双向通信后端可以处理前端的请求并发送相应的消息给前端。这使得实时的数据交互和通信成为可能,为应用程序添加了更多实时性和交互性。 需要注意的是,在实现WebSocket通信时,我们需要确保Vue和Spring Boot的版本兼容,并且正确配置相关的依赖和配置文件。同时,我们还需要考虑到安全性和性能等方面的因素,如认证和授权、连接数限制等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值