SpringBoot WebSocket 实现简单的聊天功能
2017-09-13 07:46
886 查看
前言
什么是WebSocket
WebSocket为浏览器和服务器之间提供了双工异步通信功能,也就是说我们可以利用浏览器给服务器发送消息,服务器也可以给浏览器发送消息,目前主流浏览器的主流版本对WebSocket的支持都算是比较好的,但是在实际开发中使用WebSocket工作量会略大,
而且增加了浏览器的兼容问题,这种时候我们更多的是使用WebSocket的一个子协议stomp,利用它来快速实现我们的功能。OK,
关于WebSocket我这里就不再多说,我们主要看如何使用,如果小伙伴们有兴趣可以查看这个回答来了解更多关于WebSocket的信
息WebSocket 是什么原理?为什么可以实现持久连接。
后端
依赖
开启WebSocket基础功能<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
配置
新增一个WebSocketConfig类,继承AbstractWebSocketMessageBrokerConfigurer,定义全局的配置信息,使用SpringgBoot推荐的注解配置即JavaConfig形式。package hello; 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; /** * Author: Starry.Teng * Email: tengxing7452@163.com * Date: 17-9-12 * Time: 下午12:57 * Describe: WebSocketConfig */ @Configuration @EnableWebSocketMessageBroker //通过EnableWebSocketMessageBroker 开启使用STOMP协议来传输基于代理(message broker)的消息,此时浏览器支持使用@MessageMapping 就像支持@RequestMapping一样 public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { //配置消息代理(message broker) 设置消息连接请求的各种规范 config.enableSimpleBroker("/topic");//客户端订阅地址的前缀信息 config.setApplicationDestinationPrefixes("/app");//客户端给服务端发消息的地址的前缀 } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { //注册一个名字为"gs-guide-websocket" 的endpoint,并指定 SockJS协议;添加一个服务端点,来接收客户端的连接 registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*").withSockJS(); } }
业务逻辑
/** * Author: Starry.Teng * Email: tengxing7452@163.com * Date: 17-9-12 * Time: 下午12:57 * Describe: GreetingController */ @Controller public class GreetingController { @Autowired private SimpMessagingTemplate messagingTemplate; @MessageMapping("/hello") @SendTo("/topic/greetings") public Greeting greeting(HelloMessage message) throws Exception { Thread.sleep(1000); // simulated delay return new Greeting("Hello, " + message.getName() + "!"); } @MessageMapping("/message") //@SendTo("/topic/greetings") //接收/app/message发来的value,然后将value转发到/topic/greetings客户端 public Greeting message(String message) throws Exception{ //通过convertAndSendToUser 向用户发送信息, // 第一个参数是接收消息的用户,第二个参数是浏览器订阅的地址,第三个参数是消息本身 //messagingTemplate.convertAndSendToUser(); messagingTemplate.convertAndSend("/topic/greetings",new Greeting(message)); return null; }
说明:
1. @MessageMapping注解不是@RequestMapping,后者是我们熟悉的用于http请求的映射,前者是基于webSocket协议的请求。但是理解都很简单。
2. SimpMessagingTemplate
SimpMessagingTemplate是Spring-WebSocket内置(就是封装起来的和SDR差不多,很方便)的一个消息发送工具,可以将消息发送到指定的客户端。
3. @SendTo这个注解就是将信息分发到订阅者 ,和messagingTemplate.convertAndSend()等价。
前端
在resources目录下新建一个static目录(springBoot默认路径),在static下新建index.html和app.jsindex.html
<!DOCTYPE html> <html> <head> <title>Hello WebSocket</title> <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="/main.css" rel="stylesheet"> <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> <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable Javascript and reload this page!</h2></noscript> <div id="main-content" class="container"> <div class="row"> <div class="col-md-6"> <form class="form-inline"> <div class="form-group"> <label for="connect">WebSocket connection:</label> <button id="connect" class="btn btn-default" type="submit">Connect</button> <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect </button> </div> </form> </div> <div class="col-md-6"> <form class="form-inline"> <div class="form-group"> <label for="name">What is your name?</label> <input type="text" id="name" class="form-control" placeholder="Your name here..."> </div> <button id="send" class="btn btn-default" type="submit">Send</button> </form> </div> </div> <div class="row"> <div class="col-md-12"> <table id="conversation" class="table table-striped"> <thead> <tr> <th>Greetings</th> </tr> </thead> <tbody id="greetings"> </tbody> </table> </div> <div class="col-md-12"> <label>write message:</label> <input type="text" name="mysend" id="mysend"/> <button id="mybutton" value="send">发送</button> </div> </div> </form> </div> </body> </html>
app.js
var stompClient = null; function setConnected(connected) { $("#connect").prop("disabled", connected); $("#disconnect").prop("disabled", !connected); if (connected) { $("#conversation").show(); } else { $("#conversation").hide(); } $("#greetings").html(""); } function connect() { var socket = new SockJS('/gs-guide-websocket'); //构建一个SockJS对象 stompClient = Stomp.over(socket); //用Stomp将SockJS进行协议封装 stompClient.connect({}, function (frame) { setConnected(true); console.log('Connected: ' + frame); /** 订阅了/topic/greetings 发送的消息,这里雨在控制器的 convertAndSendToUser 定义的地址保持一致, * 这里多用了一个/user,并且这个user 是必须的,使用user 才会发送消息到指定的用户。 * */ stompClient.subscribe('/topic/greetings', function (greeting) { showGreeting(JSON.parse(greeting.body).content); }); }); } function disconnect() { if (stompClient !== null) { stompClient.disconnect(); } setConnected(false); console.log("Disconnected"); } function sendName() { /*消息发送*/ stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()})); } function showGreeting(message) { $("#greetings").append("<tr><td>" + message + "</td></tr>"); } function sendMessage() { stompClient.send("/app/message", {}, JSON.stringify({'message': $("#mysend").val()})); } $(function () { $("form").on('submit', function (e) { e.preventDefault(); }); $( "#connect" ).click(function() { connect(); }); $( "#disconnect" ).click(function() { disconnect(); }); $( "#send" ).click(function() { sendName(); }); $( "#mybutton").click(function (){ sendMessage(); }); });
说明:
1. 重要的我app.js已经注释了,其他的就是js能力了
2. 说一下sockjs.js和stomp.js
SockJS: SockJS 是一个浏览器上运行的 JavaScript 库,如果浏览器不支持 WebSocket,该库可以模拟对 WebSocket 的支持,实现浏览器和 Web 服务器之间低延迟、全双工、跨域的通讯通道。 Stomp Stomp 提供了客户端和代理之间进行广泛消息传输的框架。Stomp 是一个非常简单而且易用的通讯协议实现,尽管代理端的编写可能非常复杂,但是编写一个 Stomp 客户端却是很简单的事情,另外你可以使用 Telnet 来与你的 Stomp 代理进行交互。
验证
$ mvn clean package spring-boot:run
浏览器:http://localhost:8080/ ,点击connect,输入用户可以聊天了,请看下面截图:
在浏览器新开tab页面
成功对不对。
后记
代码在github:我的github在线实时体验:点击实时体验
参考文章
http://spring.io/guides/gs/messaging-stomp-websocket/ 官方推荐http://www.jianshu.com/p/60799f1356c5
http://blog.csdn.net/u011072139/article/details/60768663
相关文章推荐
- 在Spring Boot框架下使用WebSocket实现聊天功能
- 在Spring Boot框架下使用WebSocket实现聊天功能
- 在Spring Boot框架下使用WebSocket实现聊天功能
- 在Spring Boot框架下使用WebSocket实现聊天功能
- 在Spring Boot框架下使用WebSocket实现聊天功能
- springboot整合tomcat自带的websocket实现在线聊天及象棋网页对战功能
- 在Spring Boot框架下使用WebSocket实现聊天功能
- SpringBoot+Websocket实现一个简单的网页聊天功能代码
- Spring 学习——基于Spring WebSocket 和STOMP实现简单的聊天功能
- 在Spring Boot框架下使用WebSocket实现聊天功能
- Spring 学习——基于Spring WebSocket 和STOMP实现简单的聊天功能
- 在Spring Boot框架下使用WebSocket实现聊天功能
- spring boot+mvc+mybatis+netty-sokey.io+html+js实现简单即时通讯聊天系统
- SpringBoot实现简单的注册与登陆功能
- javaweb webSocket 实现简单的点对点聊天功能
- SpringBoot整合WebSocket实现实时消息群发功能
- javaweb webSocket 实现简单的点对点聊天功能
- SpringBoot+thymeleaf简单实现登陆注册及记账功能
- Spring+JMS+使用JMS+ActiveMQ中间件+实现简单聊天功能的小例子
- Netty 实现 WebSocket 聊天功能