springboot整合websocket两种方式

本文介绍了两种在SpringBoot中整合WebSocket的方法:1) 利用html5原生支持,通过ServerEndpointExporter和serverEndpoint配置;2) 使用STOMP协议,添加websocket配置,重写DefaultHandshakeHandler并实现WebSocketMessageBrokerConfigurer,前端使用Vue实现订阅和发送消息。
摘要由CSDN通过智能技术生成

方式1:html5原生支持方式

向spring容器中注入一个ServerEndpointExporter
package com.tinet.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @author dsx
 */
@Configuration
public class WebsocketConfig {
   

    /**
     * ServerEndpointExporter 作用
     *
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
   
        return new ServerEndpointExporter();
    }
}

添加一个serverEndpoint

用于给前端建立连接的server

package com.tinet.websocket.config;

import com.alibaba.fastjson.JSON;
import com.tinet.websocket.pojo.MessageBody;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author DENGSHAOXIANG
 */
@ServerEndpoint("/websocket/test/{userId}")
@Component
public class WebsocketServer {
   

    public WebsocketServer() {
   
        //每当有一个连接,都会执行一次构造方法
        System.out.println("新的连接。。。");
    }

    /**
     * 存放当前连接数
     */
    private static final AtomicInteger COUNT = new AtomicInteger();


    /**
     * 存放所有的连接
     */
    private static final ConcurrentHashMap<String, Session> SESSIONS = new ConcurrentHashMap<>();


    //发送消息
    public void sendMessage(Session toSession, String message) {
   
        if (toSession != null) {
   
            try {
   
                toSession.getBasicRemote().sendText(message);
            } catch (IOException e) {
   
                e.printStackTrace();
            }
        } else {
   
            System.out.println("对方不在线");
        }
    }

    public void sendMessageToUser(String user, String message) {
   
        Session toSession = SESSIONS.get(user);
        sendMessage(toSession, message);
    }


    @OnMessage
    public void onMessage(String message) {
   
        System.out.println("服务器收到消息:" + message);
        MessageBody messageBody = JSON.parseObject(message, MessageBody.class);
        String userId = messageBody.getUserId();
        sendMessageToUser(userId, messageBody.getMessage());


    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
   
        if (SESSIONS.get(userId) != null) {
   
            return;
        }
        SESSIONS.put(userId, session);
        COUNT.incrementAndGet();
        System.out.println(userId + "上线了,当前在线人数:" + COUNT);

    }

    @OnClose
    public void onClose(@PathParam("userId") String userId) {
   
        SESSIONS.remove(userId);
        COUNT.decrementAndGet();
        System.out.println(userId + "下线了ÿ
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值