vue集成websocket(无发送)

<template></template>
<script>
export default {
//自己选择初始化位置
  created () {
    this.initWebSocket()
  },
  methods: {
  //初始化连接
    initWebSocket: function () {
      //此处为服务端地址
      let host = window.location.hostname
      const url = `ws://${host}:9010/xxxxxx/websocket/123`
      this.websock = new WebSocket(url)
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onmessage = this.websocketonmessage
    },
    websocketonopen: function () { },
    websocketonerror: function (e) {
      this.$message.error('网络连接失败!')
    },
    //接受服务端消息
    websocketonmessage: function ({ data }) {
    },
    //关闭连接
    websocketclose: function (e) { }
  }
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中集成WebSocket可以通过以下步骤实现: 1. 首先,在pom.xml文件中添加WebSocket的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建一个WebSocketConfig类,用于配置WebSocket相关的参数和处理器: ``` @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new WebSocketHandler(), "/websocket"); // 指定WebSocket处理器和连接的路径 } } ``` 3. 创建一个WebSocketHandler类,实现WebSocketHandler接口: ``` @Component public class WebSocketHandler extends TextWebSocketHandler { private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // 处理收到的文本消息 String payload = message.getPayload(); // 发送消息给所有连接的客户端 for (WebSocketSession webSocketSession : sessions) { webSocketSession.sendMessage(new TextMessage(payload)); } } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } } ``` 4. 在Vue中使用WebSocket连接服务器: ``` new Vue({ created() { this.socket = new WebSocket('ws://localhost:8080/websocket'); this.socket.onmessage = this.handleMessage; }, methods: { handleMessage(event) { // 收到消息后的处理逻辑 } } }) ``` 以上是Spring Boot和Vue集成WebSocket的基本步骤。通过配置WebSocketConfig类和创建WebSocketHandler类实现服务器端的消息处理和推送,然后在Vue中创建WebSocket对象进行连接并处理收到的消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值