<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                [TOC] # 簡介 springboot的組件`spring-boot-starter-websocket` ~~~ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ~~~ | 事件 | 事件處理程序 | 描述 | | --- | --- | --- | | open | Socket onopen | 連接建立時觸發 | | message | Socket onmessage | 客戶端接收服務端數據時觸發 | | error | Socket onerror | 通訊發生錯誤時觸發 | | close | Socket onclose | 鏈接關閉時觸發 | ~~~ var ws = new WebSocket("ws://localhost:8080"); ws.onopen = function(evt) { console.log("Connection open ..."); ws.send("Hello WebSockets!"); }; ws.onmessage = function(evt) { console.log( "Received Message: " + evt.data); ws.close(); }; ws.onclose = function(evt) { console.log("Connection closed."); }; ~~~ # 聊天室 ## 前端 * 加入聊天室,是建立連接onopen * 退出聊天室, 關閉連接onclose * 發送消息,調用onmessage * 異常時退出,對應onerror ~~~ <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>聊天室</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- <link href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">--> </head> <body class="container" style="width: 60%"> <div class="form-group" ></br> <h5>聊天室</h5> <textarea id="message_content" class="form-control" readonly="readonly" cols="50" rows="10"></textarea> </div> <div class="form-group" > <label for="in_user_name">用戶姓名 &nbsp;</label> <input id="in_user_name" value="" class="form-control" /></br> <button id="user_join" class="btn btn-success" >加入聊天室</button> <button id="user_exit" class="btn btn-warning" >離開聊天室</button> </div> <div class="form-group" > <label for="in_room_msg" >群發消息 &nbsp;</label> <input id="in_room_msg" value="" class="form-control" /></br> <button id="user_send_all" class="btn btn-info" >發送消息</button> </div> </body> <script type="text/javascript"> $(document).ready(function(){ var urlPrefix ='ws://localhost:8085/chat-room/'; var ws = null; $('#user_join').click(function(){ var username = $('#in_user_name').val(); if(username==''){ alert("請輸入用戶名!"); return; } var url = urlPrefix + username; ws = new WebSocket(url); ws.onopen = function () { console.log("建立 websocket 連接..."); }; ws.onmessage = function(event){ //服務端發送的消息 $('#message_content').append(event.data+'\n'); }; ws.onclose = function(){ $('#message_content').append('用戶['+username+'] 已經離開聊天室!'); console.log("關閉 websocket 連接..."); } }); //客戶端發送消息到服務器 $('#user_send_all').click(function(){ var msg = $('#in_room_msg').val(); if(msg==''){ alert("請填寫消息!"); return; } if(ws && msg!=''){ ws.send(msg); } }); // 退出聊天室 $('#user_exit').click(function(){ if(ws){ ws.close(); } }); }) </script> </html> ~~~ ## 啟動類 ~~~ @EnableWebSocket @SpringBootApplication public class UserApplication { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(UserApplication.class, args); } @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } ~~~ ## websocket工具類 ~~~ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.websocket.RemoteEndpoint; import javax.websocket.Session; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public final class WebSocketUtils { private static final Logger logger = LoggerFactory.getLogger(WebSocketUtils.class); //存儲websocket session,在線用戶 public static final Map<String, Session> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>(); /** * @param session 用戶session * @param message 發送內容 */ public static void sendMessage(Session session, String message) { if (session == null) { return; } //獲取這個用戶的地址 final RemoteEndpoint.Basic basic = session.getBasicRemote(); if (basic == null) { return; } try { //給這個地址發消息 basic.sendText(message); } catch (IOException e) { logger.error("send message exception ", e); } } /** * 聊天室消息,所有用戶可見,每次消息觸發就是遍歷所有在線用戶,給每個用戶發消息 * @param message */ public static void sendMessageAll(String message) { ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, message)); } } ~~~ ## websocket接收地址處理類 先導入工具類的這個2個靜態 ~~~ import static com.jdxia.user.utils.WebSocketUtils.ONLINE_USER_SESSIONS; import static com.jdxia.user.utils.WebSocketUtils.sendMessageAll; ~~~ 寫處理程序 ~~~ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RestController; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import static com.jdxia.user.utils.WebSocketUtils.ONLINE_USER_SESSIONS; import static com.jdxia.user.utils.WebSocketUtils.sendMessageAll; @RestController @ServerEndpoint("/chat-room/{username}") //表示監聽這個地址的websocket信息 public class ChatRoomServerEndpoint { private static final Logger logger = LoggerFactory.getLogger(ChatRoomServerEndpoint.class); @OnOpen public void openSession(@PathParam("username") String username, Session session) { //用戶登錄的時候,把用戶信息放入session中 ONLINE_USER_SESSIONS.put(username, session); String message = "歡迎用戶[" + username + "]來到聊天室"; logger.info("用戶登錄: " + message); sendMessageAll(message); } //監聽發送消息事件 @OnMessage public void onMessage(@PathParam("username") String username, String message) { logger.info("發送消息: " + message); sendMessageAll("用戶[" + username + "] : " + message); } @OnClose public void onClose(@PathParam("username") String username, Session session) { //當前session移除 ONLINE_USER_SESSIONS.remove(username); //并且通知他人退出 sendMessageAll("用戶[" + username + "] 已經離開聊天室"); try { session.close(); } catch (IOException e) { logger.error("onClose error: ", e); } } @OnError public void onError(Session session, Throwable throwable) { try{ session.close(); } catch (IOException e) { logger.error("onError exception: ", e); } logger.info("Throwable msg: " + throwable.getMessage()); } } ~~~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看