天天看點

9、springboot和websocket的內建,實作簡單的單發和群發消息建立簡單的springboot項目,引入socket相關的jar包在resources/templates/ws.html檔案真實頁面,啟動項目之後通路:http://localhost:8080/wswebmvc的視圖控制器配置websocket的ServerEndpointExporter 群發和單發消息調用的接口:消息發送的方法springboot啟動類啟動服務通過調用接口,讓伺服器群發和單發消息

建立簡單的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檔案

注:(關閉掉這個頁面之後,socket連接配接就會關閉)

//前後端分離的使用域名的時候,記得nginx把端口打開,因為springboot項目和websocket使用不同的端口,如果nginx沒有打開websocket端口監聽,前端是連結不上的

socket = new WebSocket("ws://localhost:8080/ws/asset");

<!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定義的位址
        //前後端分離的使用域名的時候,記得nginx把端口打開
        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連接配接就會關閉)
        socket.onclose = function () {
            console.log("Socket已關閉");
        };
        //發生了錯誤事件
        socket.onerror = function () {
            alert("Socket發生了錯誤");
        }

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

</body>
</html>
           

真實頁面,啟動項目之後通路:http://localhost:8080/ws

9、springboot和websocket的內建,實作簡單的單發和群發消息建立簡單的springboot項目,引入socket相關的jar包在resources/templates/ws.html檔案真實頁面,啟動項目之後通路:http://localhost:8080/wswebmvc的視圖控制器配置websocket的ServerEndpointExporter 群發和單發消息調用的接口:消息發送的方法springboot啟動類啟動服務通過調用接口,讓伺服器群發和單發消息

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,每開一個頁面,都能收到伺服器定時群發消息

9、springboot和websocket的內建,實作簡單的單發和群發消息建立簡單的springboot項目,引入socket相關的jar包在resources/templates/ws.html檔案真實頁面,啟動項目之後通路:http://localhost:8080/wswebmvc的視圖控制器配置websocket的ServerEndpointExporter 群發和單發消息調用的接口:消息發送的方法springboot啟動類啟動服務通過調用接口,讓伺服器群發和單發消息

通過調用接口,讓伺服器群發和單發消息

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

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

繼續閱讀