SpringBoot中WebSocket的应用:聊天室
2017-09-25 22:39
375 查看
springboot中使用的websocket的子协议STOMP。STOMP协议是一个更高级别的协议,使用一个基于帧结构的格式来定义消,与HTTP的request和response类似。
1.新建一个springboot工程,添加websocket和Thymleaf依赖
thymeleaf相关的知识参考我的另一篇博文:http://blog.csdn.net/JHYPXS/article/details/78080231<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2.添加websocket配置
package com.cvsea.websocket.config; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{ @Override public void registerStompEndpoints(StompEndpointRegistry P_Registry) { P_Registry.addEndpoint("endpointCvsea").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry P_Registry) { P_Registry.enableSimpleBroker("/topic"); } }
3.接受到的消息Entity
package com.cvsea.websocket.model; public class CvseaMessage { private String content; public String getContent() { return this.content; } }
4.发送到客户端的消息Entity
package com.cvsea.websocket.model; public class CvseaResponeMessage { private String content; public CvseaResponeMessage(String P_Message) { this.content=P_Message; } public String getContent() { return this.content; } }
5.前端控制器
package com.cvsea.websocket.controller; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; import com.cvsea.websocket.model.CvseaMessage; import com.cvsea.websocket.model.CvseaResponeMessage; @Controller public class WebSocketController { @MessageMapping("/welcome") @SendTo("/topic/getResponse") public CvseaResponeMessage response(CvseaMessage P_Message) { return new CvseaResponeMessage(P_Message.getContent()); } }
6.添加js脚本到/src/main/resources/static/
js下载地址:#stomp.min.js存放在/websocket/js/ http://www.bootcdn.cn/stomp.js/ #sockjs.min.js存放在/websocket/js/ http://www.bootcdn.cn/sockjs-client/ #jquery.min.js存放在/common/js/ http://www.bootcdn.cn/jquery/[/code]7.前端thymeleaf模板页面/src/main/resources/templates/websocket/ws.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>websocket</title> </head> <body onload="disconnect()"> <noscript> <h2 style="color: #ff0000">您的浏览器不支持websocket,请升级</h2> </noscript> <div> <div> <button id="connect" onclick="connect();">连接</button> <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button> </div> <div id="conversation" style="visibility: hidden"> <label>请输入聊天内容:</label><input type="text" id="message" /> <button id="sendmessage" onclick="sendMessage();">发送</button> <ul id="response"> </ul> </div> </div> <script th:src="@{/websocket/js/sockjs.min.js}"></script> <script th:src="@{/websocket/js/stomp.min.js}"></script> <script th:src="@{/common/js/jquery.min.js}"></script> <script type="text/javascript"> var stompClient = null; function setConnected(connected) { document.getElementById("connect").disabled = connected; document.getElementById("disconnect").disabled = !connected; document.getElementById("conversation").style.visibility = connected ? "visible" : "hidden"; $("#response").html(); } function connect() { var socket = new SockJS("/endpointCvsea"); stompClient = Stomp.over(socket); stompClient.connect({}, function(frame) { setConnected(true); console.log("Connected:" + frame); stompClient.subscribe("/topic/getResponse", function(response) { showResponse(JSON.parse(response.body).content); }); }); } function disconnect() { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); console.log("disconnnected"); } function sendMessage() { var message = $("#message").val(); stompClient.send("/welcome", {}, JSON.stringify({ "content" : message })); } function showResponse(message) { var response = $("#response"); response.append("<li>" + message + "</li>"); } </script> </body> </html>8.程序入口
package com.cvsea; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @SpringBootApplication public class Learning1Application { @RequestMapping("/websocket") public String ws(Model model) { return "websocket/ws"; } public static void main(String[] args) { SpringApplication.run(Learning1Application.class, args); } }9.运行测试,可以使用不同的浏览器打开这个页面,查看效果
相关文章推荐
- SpringBoot学习——websocket组件学习在线聊天室demo
- Spring Boot 构建应用——基于 WebSocket 的消息推送
- 基于 SpringBoot 和 webSocket 的匿名聊天室
- springboot中websocket的简单应用
- SpringBoot中WebSocket的应用:即时通讯
- 【系统学习SpringBoot】再遇Spring Data JPA之JPA应用详解(自定义查询及复杂查询)
- Spring Boot应用的后台运行配置
- web即时通讯2--基于Spring websocket达到web聊天室
- SpringBoot应用与原理之开发环境搭建
- 打造完美接口文档 - 发布springboot应用到阿里云服务器
- spring boot应用启动原理分析
- 补习系列-springboot-restful应用
- 如何优雅的打包 Spring Boot 应用
- 【Spring Boot】02 - 用Spring Boot创建Java应用
- spring boot中使用webSocket组件实现实时通讯
- spring boot 实际应用(四)log4j2 整合
- 缺省配置Springboot Web应用运行中DispatchServlet的初始化
- SpringBoot学习(四)SpringBoot和WebSocket
- Spring boot 中Spring data JPA的应用(一)
- 使用 Spring Boot 快速构建 Spring 框架应用