springboot整合websocket


1、添加依賴

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


        <dependency>
            <!-- fastjson -->
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

2、添加配置文件

package com.cosmo.sandtable.configure;

import com.cosmo.sandtable.service.ReceiveDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.annotation.PostConstruct;

/**
 * @author 12077
 */
@Configuration
public class WebSocketConfig {

    /**
     * 注入一個ServerEndpointExporter,該Bean會自動注冊使用@ServerEndpoint注解申明的websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
package com.cosmo.sandtable.websocket;
import com.cosmo.sandtable.service.ReceiveDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * 前后端交互的類實現消息的接收推送(自己發送給所有人(不包括自己))
 *
 * @author 12077
 * @ServerEndpoint(value = "/test/oneToMany") 前端通過此URI 和后端交互,建立連接
 */
@Slf4j
@ServerEndpoint(value = "/sandTable")
@Service
public class OneToManyWebSocket {

    /**
     * 記錄當前在線連接數
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 存放所有在線的客戶端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    private static ReceiveDataService receiveDataService;

    /**
     * 解決authwire不能注入問題 ReceiveDataService
     * @param receiveDataService
     */
    @Autowired
    public void setApplicationContext(ReceiveDataService receiveDataService){
        OneToManyWebSocket.receiveDataService=receiveDataService;
    }

    /**
     * 連接建立成功調用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在線數加1
        clients.put(session.getId(), session);
        log.info("有新連接加入:{},當前在線人數為:{}", session.getId(), onlineCount.get());
        receiveDataService.lightResetLoop(1);
    }

    /**
     * 連接關閉調用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在線數減1
        clients.remove(session.getId());
        log.info("有一連接關閉:{},當前在線人數為:{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客戶端消息后調用的方法
     *
     * @param message 客戶端發送過來的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服務端收到客戶端[{}]的消息:{}", session.getId(), message);
        this.sendMessage(message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("發生錯誤");
        error.printStackTrace();
    }

    /**
     * 群發消息
     *
     * @param message 消息內容
     */
    private void sendMessage(String message, Session fromSession) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            // 排除掉自己
            if (!fromSession.getId().equals(toSession.getId())) {
                log.info("服務端給客戶端[{}]發送消息{}", toSession.getId(), message);
                toSession.getAsyncRemote().sendText(message);
            }
        }
    }

    public void sendMessage(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            toSession.getAsyncRemote().sendText(message);
        }
    }
}

 

websocket不能注入報空指針:https://blog.csdn.net/qq_40136782/article/details/109078750

https://www.cnblogs.com/xuwenjin/p/12664650.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM