springboot整合websocket实现群聊
- 1.依賴
- 2.websocket配置:
- 3.前端
- 4.注意事項
效果:
也可以打開新窗口連接一個新用戶發消息
1.依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><dependency><groupId>org.webjars</groupId><artifactId>stomp-websocket</artifactId><version>2.3.3</version></dependency><dependency><groupId>org.webjars</groupId><artifactId>jquery</artifactId><version>2.1.4</version></dependency><dependency><groupId>org.webjars</groupId><artifactId>sockjs-client</artifactId><version>1.1.2</version></dependency><dependency><groupId>org.webjars</groupId><artifactId>webjars-locator-core</artifactId></dependency>除了第一個之外其他的都是前端的依賴包
2.websocket配置:
@Componentpublic class WebSocketBean { private Session session; } @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry){registry.enableSimpleBroker("/topic");registry.setApplicationDestinationPrefixes("/socket");}@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry){registry.addEndpoint("/chat").withSockJS();}} @Controller public class GreetingController {@MessageMapping("/hello")@SendTo("/topic/greetings")public Message greeting(Message message){return message;} // ,@MessageMapping("/hello")注解的方法將用來接收 // “/app/hello”路徑發送來的消息,在注解方法中對消息進行處理后, // 再將消息轉發到@SendTo定義的路徑上, // 而@SendTo路徑是一個前綴為“/topic”的路徑, // 因此該消息將被交給消息代理broker,再由broker進行廣播。} @Data public class Message {private String name;private String title;private String content; }3.前端
<!DOCTYPE html> <html lang="en"> <head><title>群聊</title><meta charset="UTF-8"><title>Title</title><script src = "/webjars/jquery/jquery.min.js"></script><script src = "/webjars/sockjs-client/sockjs.min.js"></script><script src="/webjars/stomp-websocket/stomp.min.js"></script><script src = "/app.js"></script> </head><body> <div><label for="name">用戶名:</label><input type="text" id="name" placeholder="用戶名"> </div> <div><label for="title">標題:</label><input type="text" id="title" placeholder="標題"> </div> <div><button id="connect" type="button">連接</button><button id="disconnect" type="button" disabled="disabled">斷開</button> </div> <label for="name">請輸入聊天內容:</label> <input type="text" id="content" placeholder="聊天內容"> <button id="send" type="button">發送</button> <div id="greetings"><div id="conversation" style="display: none">群聊中</div> </div> </body> </html>app.js:
var stompClient = null function setConnected(connected) {$("#connect").prop("disabled", connected);$("#disconnect").prop("disabled", !connected);if (connected) {$("#conversation").show();$("#chat").show();} else {$("#conversation").hide();$("#chat").hide();}$("#greetings").html("") }function connect(){if (!$("#name"). val()) {return;}var socket =new SockJS('/chat');stompClient =Stomp.over(socket);stompClient.connect({}, function (frame){setConnected(true);stompClient. subscribe ('/topic/greetings', function (greeting){showGreeting (JSON. parse (greeting. body));})}) } function disconnect(){if (stompClient != null) {stompClient.disconnect();}setConnected(false);}function sendName() {stompClient.send("/socket/hello", {},JSON.stringify({'name': $("#name").val(), 'title':$("#title").val(),'content': $("#content").val()}));}function showGreeting(message) {$("#greetings").append("<div>" + message.name + ": " + message.content +":"+ message.title+ "</div>");}$(function (){ $("#connect" ).click(function() { connect(); }) $("#disconnect" ).click(function() { disconnect(); }) $("#send").click(function (){ sendName () })});首先使用SockJS建立連接,然后創建一個STOMP實例發起連接請求,在連接成功的回調方法中,首先調用setConnected(true);方法進行頁面的設置,然后調用STOMP中的subscribe方法訂閱服務端發送回來的消息,并將服務端發送來的消息展示出來(使用showGreeting方法)。
4.注意事項
message一定要有get 和set方法,且屬性名要與前端的一一對應
關于前后端中的路徑:
registry.addEndpoint("/chat").withSockJS();
定義一個前綴為/chat的endPoint,并開啟sockjs支持,客戶端通過這里配置的URL來建立websocket連接
即
var socket =new SockJS(’/chat’);
registry.enableSimpleBroker("/topic");
設置消息代理的前綴,如果消息的前綴是/topic就會轉發給消息代理
@SendTo("/topic/greetings") 將消息轉發到sento對應的路徑上
前端js:
stompClient. subscribe (’/topic/greetings’, function (greeting){
showGreeting (JSON. parse (greeting. body));
})
@MessageMapping("/hello")
用來接收/socket/hello路徑發過來的消息,然后再轉發到@SendTo定義的路徑上
總結
以上是生活随笔為你收集整理的springboot整合websocket实现群聊的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自定义异常时exception is n
- 下一篇: springboot整合shiro和se