當前位置:
                    首頁 >
                            前端技术
>                            javascript
>内容正文                
                        
                    javascript
SpringBoot使用Websocket
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                SpringBoot使用Websocket
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                webSocket是HTML5的一種新協議,它實現了服務端與客戶端的全雙工通信,建立在傳輸層,tcp協議之上,即瀏覽器與服務端需要先建立tcp協議,再發送webSocket連接建立請求。webSocket的連接:客戶端發送請求信息,服務端接受到請求并返回相應的信息。連接建立。客戶端發送http請求時,通過 Upgrade:webSocket Connection:Upgrade 告知服務器需要建立的是webSocket連接,并且還會傳遞webSocket版本號,協議的字版本號,原始地址,主機地址, webSocket相互通信的Header很小,大概只有2Bytes
SpringBoot結合WebSocket實現群發消息
一. 消息群發
1. 導入依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId> </dependency>2. 新建WebSocket配置類
@Configuration public class WebsocketConfiguration {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();} }3. 新建WebSocket服務端
@ServerEndpoint("/test") @Component @Slf4j public class MyWebsocketServer {/*** 存放所有在線的客戶端*/private static Map<String, Session> clients = new ConcurrentHashMap<>();@OnOpenpublic void onOpen(Session session) {log.info("有新的客戶端連接了: {}", session.getId());//將新用戶存入在線的組clients.put(session.getId(), session);}/*** 客戶端關閉* @param session session*/@OnClosepublic void onClose(Session session) {log.info("有用戶斷開了, id為:{}", session.getId());//將掉線的用戶移除在線的組里clients.remove(session.getId());}/*** 發生錯誤* @param throwable e*/@OnErrorpublic void onError(Throwable throwable) {throwable.printStackTrace();}/*** 收到客戶端發來消息* @param message 消息對象*/@OnMessagepublic void onMessage(String message) {log.info("服務端收到客戶端發來的消息: {}", message);this.sendAll(message);}/*** 群發消息* @param message 消息內容*/private void sendAll(String message) {for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {sessionEntry.getValue().getAsyncRemote().sendText(message);}} }4. 啟動后,客戶端連接websocket
5. 客戶端發送消息得到的響應和服務端的響應
- 客戶端
 - 服務端
 
SpringBoot結合WebSocket實現一對一發送消息
導入依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId> </dependency> <dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId> </dependency>新建Websocket配置類
@Configuration public class WebsocketConfiguration {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();} }新建消息對象
@Data @Builder @NoArgsConstructor @AllArgsConstructor public class Message {private String userId;private String message; }新建websocket服務
@ServerEndpoint("/test-one") @Component @Slf4j public class MyOneToOneServer {/*** 用于存放所有在線客戶端*/private static Map<String, Session> clients = new ConcurrentHashMap<>();private Gson gson = new Gson();@OnOpenpublic void onOpen(Session session) {log.info("有新的客戶端上線: {}", session.getId());clients.put(session.getId(), session);}@OnClosepublic void onClose(Session session) {String sessionId = session.getId();log.info("有客戶端離線: {}", sessionId);clients.remove(sessionId);}@OnErrorpublic void onError(Session session, Throwable throwable) {throwable.printStackTrace();if (clients.get(session.getId()) != null) {clients.remove(session.getId());}}@OnMessagepublic void onMessage(String message) {log.info("收到客戶端發來的消息: {}", message);this.sendTo(gson.fromJson(message, Message.class));}/*** 發送消息** @param message 消息對象*/private void sendTo(Message message) {Session s = clients.get(message.getUserId());if (s != null) {try {s.getBasicRemote().sendText(message.getMessage());} catch (IOException e) {e.printStackTrace();}}} }測試
- 上線兩個客戶端
 - 使用其中一個客戶端發送消息給另外一個,只需要帶上另外一個客戶端的id
 - 接收方客戶端
 
總結
以上是生活随笔為你收集整理的SpringBoot使用Websocket的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: python3随笔-特征值,特征向量,逆
 - 下一篇: TensorFlow随笔-多分类单层神经