【Web系列十七】Springboot+Vue实现websocket通信

目录

前言

SpringBoot

使用maven添加依赖

创建websocket服务

创建配置文件 

Vue

创建websocket类

初始化

测试

连接与通信

 断开连接

参考资料


前言

        想实现websocket通信并不复杂,这篇文章列举了多种选择,感兴趣的可以移步了解。

一文搞懂四种 WebSocket 使用方式,建议收藏! - 知乎 (zhihu.com)

        而本文是使用ServerEndpoint实现的。

SpringBoot

使用maven添加依赖

        maven搭建springboot环境可以参考博主的这篇文章。

【web系列十六】idea下使用Maven搭建spring boot开发环境_Nicholson07的博客-CSDN博客

        找到pom.xml添加以下内容

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

创建websocket服务

        创建service文件夹及WebSocket.java

@Component
@Slf4j
@ServerEndpoint(value = "/websocket/{sessionId}")
public class WebSocket {
    
    public static int onlineCount = 0;
	
    public static Map<String, WebSocket> clients = new HashMap<String, WebSocket>();
    public Session session;  
    public String  sessionId;  
	
    public String getsessionId() {
        return sessionId;
    }
 
    public static void sendMessageTo(JSONObject json) {  
        log.warn("sendMsg:"+json);
        for (WebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(json.toJSONString());  
        }
    }
	
    @OnOpen  
    public void onOpen(@PathParam("sessionId") String sessionId, Session session) throws IOException { 
        this.sessionId = sessionId;  
        this.session = session;  
        clients.put(session.getId(), this);  
        log.warn("已连接:"+sessionId);  
		JSONObject msg = new JSONObject();
		msg.put("msg", "spring send msg");
		this.sendMessageTo(msg);
    }  
  
    @OnClose  
    public void onClose() throws IOException {  
        log.warn("断开"+sessionId);
        clients.remove(session.getId()); 
    }  
  
    //收到客户端消息后调用的方法
    @OnMessage  
    public void onMessage(String message) throws IOException {   
        if(message.equals("ping")) {
            this.session.getAsyncRemote().sendText("pang");  
        }else if("close".equals(message)) {
            onClose();
            this.session.close();
        }else {
            log.warn(this.sessionId+"收到 "+message);
        }
    }
	
    @OnError  
    public void onError(Session session, Throwable error) {  
        error.printStackTrace();  
    }
  
    public static synchronized Map<String, WebSocket> getClients() {  
        return clients;  
    } 
    
    public static synchronized int getOnlineCount() {  
        return clients.size();  
    }  
}

创建配置文件 

        创建config文件夹及WebSocketConfig.java

@configurature
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

Vue

创建websocket类

        用ws.ts封装websocket

class WS {
    ip: string
    port: string
    closure: Function
    ws: WebSocket
    constructor (ip: string, port: string) {
        thie.ip = ip
        this.port = port
        this.ws = new WebSocket('ws://' + ip + ':' + port)
        
        this.ws.open = function () {
            console.log('acquiring data')
        }    
        
        this.ws.onmessage = function (ev: any) {
            console.log('收到spring消息', ev.data)
        }

        this.ws.onclose = function (ev: any) {
            alert('connection closed!')
        }

        this.ws.onerror = function (ev: any) {
            alert('connection error!')
        }

        this.closure = function () {
            this.ws.close()
        }
     }
}

初始化

<script setup lang='ts'>
import { onMounted, onUnmounted } from 'vue'
import { WS } from '@/utils/ws'

let ws: WS

onMounted(() => {
    ws = new WS('192.168.1.200', '8891/websocket/test')
})

onUnmounted(() => {
    ws.closure()
})
</script>

测试

连接与通信

        vue

         springboot

 断开连接

        vue

         springboot

 

参考资料

【web系列十六】idea下使用Maven搭建spring boot开发环境_Nicholson07的博客-CSDN博客

一文搞懂四种 WebSocket 使用方式,建议收藏! - 知乎 (zhihu.com)

猜你喜欢

转载自blog.csdn.net/Nichlson/article/details/127749534
今日推荐