時間:2023-07-22 09:45:01 | 來源:網(wǎng)站運營
時間:2023-07-22 09:45:01 來源:網(wǎng)站運營
springboot5分鐘快速搭建WEBSCOKET聊天室:Websocket 聊天室<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>chat room websocket</title> <link rel="stylesheet" href="bootstrap.min.css"> <script src="jquery-3.2.1.min.js" ></script></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">用戶姓名 </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" >群發(fā)消息 </label> <input id="in_room_msg" value="" class="form-control" /></br> <button id="user_send_all" class="btn btn-info" >發(fā)送消息</button></div></body><script type="text/javascript"> $(document).ready(function(){ var urlPrefix ='ws://localhost:8080/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){ //服務(wù)端發(fā)送的消息 $('#message_content').append(event.data+'/n'); }; ws.onclose = function(){ $('#message_content').append('用戶['+username+'] 已經(jīng)離開聊天室!'); console.log("關(guān)閉 websocket 連接..."); } }); //客戶端發(fā)送消息到服務(wù)器 $('#user_send_all').click(function(){ var msg = $('#in_room_msg').val(); if(msg==''){ alert("請?zhí)顚懴ⅲ?#34;); return; } if(ws && msg!=''){ ws.send(msg); } }); // 退出聊天室 $('#user_exit').click(function(){ if(ws){ ws.close(); } }); })</script></html>
這兩個文件沒有的可以直接私聊我。jquery-3.2.1.min.jsbootstrap.min.css
<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>
主要添加 Web 和 Websocket 組件。@EnableWebSocket@SpringBootApplicationpublic class WebSocketApplication { public static void main(String[] args) { SpringApplication.run(WebSocketApplication.class, args); } @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}
請求接收package com.neo.utils;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 發(fā)送內(nèi)容 */ 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("sendMessage IOException ",e); } } public static void sendMessageAll(String message) { ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, message)); }}
這樣我們在創(chuàng)建 ChatRoomServerEndpoint 類的時候就可以直接將?具類的?法和全局變量導(dǎo)?:package com.neo;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.neo.utils.WebSocketUtils.ONLINE_USER_SESSIONS;import static com.neo.utils.WebSocketUtils.sendMessageAll;@RestController@ServerEndpoint("/chat-room/{username}")public class ChatRoomServerEndpoint { private static final Logger logger = LoggerFactory.getLogger(ChatRoomServerEndpoint.class); @OnOpen public void openSession(@PathParam("username") String username, 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("發(fā)送消息:"+message); sendMessageAll("用戶[" + username + "] : " + message); } @OnClose public void onClose(@PathParam("username") String username, Session session) { //當(dāng)前的Session 移除 ONLINE_USER_SESSIONS.remove(username); //并且通知其他人當(dāng)前用戶已經(jīng)離開聊天室了 sendMessageAll("用戶[" + username + "] 已經(jīng)離開聊天室了!"); 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 excepiton",e); } logger.info("Throwable msg "+throwable.getMessage()); }}
啥這就完成了?沒錯 !關(guān)鍵詞:
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。