简单实现websocket

一、 添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二、 配置WebSocket
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;


@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new MyWebSocketHandler(), "/ws").setAllowedOrigins("*");
    }
}
三、 创建WebSocket处理器
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;




public class MyWebSocketHandler extends TextWebSocketHandler {




    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 连接建立后,可以向客户端发送消息
        session.sendMessage(new TextMessage("Connection established"));
    }




    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理收到的消息
        String payload = message.getPayload();
        System.out.println("Received message: " + payload);
        session.sendMessage(new TextMessage("Message received: " + payload));
    }




    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 连接关闭后的处理
    }
}
四、 Vue使用WebSocket
<template>
  <div id="app">
    <h1>WebSocket Demo</h1>
    <button @click="sendMessage">Send Message</button>
    <p>{{ response }}</p>
  </div>
</template>


<script>
export default {
  data() {
    return {
      websocket: null,
      response: ''
    };
  },
  mounted() {
    // 连接WebSocket服务器
    this.websocket = new WebSocket('ws://localhost:8080/ws');
    
    // 处理收到的消息
    this.websocket.onmessage = (event) => {
      this.response = event.data;
    };


    // 连接关闭的处理
    this.websocket.onclose = () => {
      console.log('WebSocket connection closed');
    };
  },
  methods: {
    sendMessage() {
      if (this.websocket) {
        this.websocket.send('Hello, server!');
      }
    }
  }
};
</script>
<style scoped>

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值