websocket 實現實時消息推送


使用場景:WebSocket可用於實現網頁版聊天室,以及服務器消息實時通知。

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

配置WebSocketConfig類

@Configuration
@EnableWebSocket
public class WebSocketConfig  {

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

配置HttpSessionWSHelper類

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;


public class HttpSessionWSHelper extends ServerEndpointConfig.Configurator{
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        HttpSession httpSession=(HttpSession) request.getHttpSession();
        sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
    }
} 

編寫webSocketSever類

import lombok.extern.slf4j.Slf4j;
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.List;
import java.util.concurrent.CopyOnWriteArraySet;


@Slf4j
@Component
@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer {

    //用來記錄當前在線連接數。
    private static int onlineCount = 0;



    /**
     * concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
     */
   public static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    //與某個客戶端的連接會話,需要通過它來給客戶端發送數據
    private Session session;
    //接收sid
    private String sid = "";

    /**
     *     * 連接建立成功調用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this); //加入set中
        addOnlineCount();//在線數加1
        log.info("有新窗口開始監聽:" + sid
                + ",當前在線人數為" + getOnlineCount());
        this.sid = sid;

//        try {
//            sendMessage("連接成功");
//            sendInfo("當前連接用戶數:" + getOnlineCount(), null);
//        } catch (IOException e) {
//            log.error("websocket IO異常");
//        }
    }


    /**
     *     * 連接關閉調用的方法
     *    
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //從set中刪除
        subOnlineCount();  //在線數減1
        log.info("有一連接關閉!當前在線人數為" + getOnlineCount());
    }

    /**
     *     * 收到客戶端消息后調用的方法
     *     *
     *     * @param message 客戶端發送過來的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到來自窗口" + sid + "的信息:" + message);
        //單用戶sid
        try {
            WebSocketServer.sendInfo(message,sid);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 群發消息
//        for (WebSocketServer item : webSocketSet) {
//            try {
//                item.sendMessage(message);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }


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

    /**
     *     * 實現服務器主動推送
     *    
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     *     * 群發自定義消息
     *     * 這里可以設定只推送給這個sid的,為null則全部推送
     */
    public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
        System.out.println("------WebSocketServer----------sendInfo-----");
        log.info("推送消息到窗口" + sid + ",推送內容:" + message);
        for (WebSocketServer item : webSocketSet) {
            try {
                //sid為null則全部推送
                if (sid == null) {
                    item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }


    }



    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }


}

測試網址: http://www.websocket-test.com/


免責聲明!

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



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