Springboot WebSocket + Vue.js 基础代码

  1. 在Springboot中,我们需要使用Stomp协议来实现WebSocket连接。首先,需要添加以下依赖项:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>webjars-locator-core</artifactId>
  <version>0.40</version>
</dependency>
<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>sockjs-client</artifactId>
  <version>1.0.2</version>
</dependency>
<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>stomp-websocket</artifactId>
  <version>2.3.3</version>
</dependency>
  1. 创建WebSocket的配置文件:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS();
    }

}

这里定义了WebSocket的消息代理和端点。

  1. 创建WebSocketController,处理WebSocket的请求:

@Controller
public class WebSocketController {

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) {
        return new Greeting("Hello, " + message.getName() + "!");
    }

    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public ChatMessage chat(ChatMessage message) {
        return new ChatMessage(message.getContent(), message.getSender());
    }

}

这里定义了两个WebSocket请求(/hello和/chat),并将它们的响应发送到特定的主题(/topic/greetings和/topic/messages)。

  1. 在Vue.js中,我们需要使用SockJS和Stomp.js库来实现WebSocket连接。首先,需要添加以下依赖项:

<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.0/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/dist/stomp.min.js"></script>
  1. 创建Vue.js组件,处理WebSocket的连接和消息:

<template>
  <div>
    <label for="name">Name:</label>
    <input v-model="name" type="text" id="name">

    <button @click="connect">Connect</button>

    <div v-if="connected">
      <label for="message">Message:</label>
      <input v-model="message" type="text" id="message">
      <button @click="sendMessage">Send</button>

      <ul>
        <li v-for="greeting in greetings" :key="greeting.id">{{ greeting.content }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        ws: null,
        connected: false,
        name: "",
        message: "",
        greetings: [],
      };
    },
    methods: {
      connect() {
        const socket = new SockJS("http://localhost:8080/websocket");
        this.ws = Stomp.over(socket);
        this.ws.connect({}, () => {
          this.connected = true;
          this.ws.subscribe("/topic/greetings", (greeting) => {
            this.greetings.push(JSON.parse(greeting.body));
          });
        });
      },
      sendMessage() {
        const message = { name: this.name };
        this.ws.send("/app/hello", {}, JSON.stringify(message));
        this.message = "";
      },
    },
  };
</script>

这里定义了一个Vue.js组件,用于建立WebSocket连接并发送和接收WebSocket消息。点击“Connect”按钮将建立WebSocket连接,然后可以发送消息并接收来自主题“/topic/greetings”的响应。

这只是一个基本的示例,您可以根据需要修改代码和逻辑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eddie_920

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值