9、springboot和websocket的集成,實現簡單的單發和羣發消息

新建簡單的springboot項目,引入socket相關的jar包

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

在resources/templates/ws.html文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>websocket測試</title>
    <style type="text/css">
        h3, h4 {
            text-align: center;
        }
    </style>
</head>
<body>

<h3>WebSocket測試</h3>
<h4>
    單發消息
    <li>url=http://localhost:8080/test/sendOne?message=單發消息內容&id=none</li>
    羣發消息
    <li>url=http://localhost:8080/test/sendAll?message=羣發消息內容</li>
</h4>
<div style="text-align:center;">
    <textarea id="content" style="width:500px;height:300px;"></textarea></div>

<script type="text/javascript">
    var socket;
    if (typeof (WebSocket) == "undefined") {
        console.log("遺憾:您的瀏覽器不支持WebSocket");
    } else {
        console.log("恭喜:您的瀏覽器支持WebSocket");

        //實現化WebSocket對象
        //指定要連接的服務器地址與端口建立連接
        //注意ws、wss使用不同的端口。我使用自簽名的證書測試,
        //無法使用wss,瀏覽器打開WebSocket時報錯
        //ws對應http、wss對應https。這個地址是endpoint定義的地址
        socket = new WebSocket("ws://localhost:8080/ws/asset");
        //連接打開事件
        socket.onopen = function () {
            console.log("Socket 已打開");
            socket.send("消息發送測試(From Client)");
        };
        //收到消息事件
        socket.onmessage = function (msg) {
            var ta = document.getElementById('content');
            ta.value = ta.value + '\n' + event.data
        };
        //連接關閉事件
        socket.onclose = function () {
            console.log("Socket已關閉");
        };
        //發生了錯誤事件
        socket.onerror = function () {
            alert("Socket發生了錯誤");
        }

        //窗口關閉時,關閉連接
        window.unload = function () {
            socket.close();
        };
    }
</script>

</body>
</html>

真實頁面,啓動項目之後訪問:http://localhost:8080/ws

webmvc的視圖控制器配置

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/ws").setViewName("/ws");
    }
}

websocket的ServerEndpointExporter 

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

羣發和單發消息調用的接口:

@RestController
@RequestMapping("/test")
@EnableScheduling
public class WsController {

    /**
     * 羣發消息接口
     * @param message
     * @return
     */
    @GetMapping("/sendAll")
    public String sendAll(@RequestParam String message){
        WebSocketServer.broadCastInfo(message);
        return "ok";
    }

    /**
     * 服務器定時羣發消息
     * @return
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public String sendAll(){
        WebSocketServer.broadCastInfo("瀏覽器收到消息:服務端定時羣發消息");
        return "ok";
    }

    /**
     * 單發消息接口
     * @param message 消息
     * @param id sessionId
     * @return
     */
    @GetMapping("/sendOne")
    public String sendOne(@RequestParam String message,@RequestParam String id){
        WebSocketServer.SendMessage(id,message);
        return "ok";
    }
}

消息發送的方法

@ServerEndpoint("/ws/asset")
@Component
public class WebSocketServer {
    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    public static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
    /**
     * 存放每個客戶端對應的session對象
     */
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session){
        SessionSet.add(session);
        int count = ONLINE_COUNT.incrementAndGet();
        log.info("有新的連接加入:{},當前連接數爲:{}",session.getId(),count);
    }

    @OnClose
    public void OnClose(Session session){
        SessionSet.remove(session);
        int count = ONLINE_COUNT.decrementAndGet();
        log.info("有連接關閉:{},當前連接數爲:{}",session.getId(),count);
    }

    @OnMessage
    public void OnMessage(String message,Session session){
        log.info("收到客戶端消息:{}",message);
        sendMessage(session,"瀏覽器收到消息:"+message);
    }

    @OnError
    public void OnError(Session session,Throwable error){
        log.error("發生錯誤:{},Session ID: {}",error.getMessage(),session.getId());
        error.printStackTrace();
    }
    public static void sendMessage(Session session,String message){
        try {
            session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)",message,session.getId()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

    }

    public static void broadCastInfo(String message) {
        for (Session session : SessionSet) {
            if(session.isOpen()){
                sendMessage(session,message);
            }

        }
    }

    public static void SendMessage(String id, String message) {
        Session session = null;
        //先通過id找到session
        for (Session s : SessionSet) {
            if(s.getId().equals(id)){
                session = s;
                break;
            }
        }
        if(session != null){
            sendMessage(session,message);
        }else{
            log.error("未找到指定的sessionId");
        }
    }
}

springboot啓動類

@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}

啓動服務

訪問http://localhost:8080/ws,多開幾個頁面訪問http://localhost:8080/ws,每開一個頁面,都能收到服務器定時羣發消息

通過調用接口,讓服務器羣發和單發消息

羣發:http://localhost:8080/test/sendAll?message=123

單發:http://localhost:8080/test/sendOne?message=單發消息內容&id=1(這裏的id是session Id)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章