一篇文章带你使用SpringBoot基于WebSocket的在线群聊实现
一、添加依赖
加入前端需要用到的依赖:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | < dependency > < groupId >org.webjars</ groupId > < artifactId >sockjs-client</ artifactId > < version >1.1.2</ version > </ dependency > < dependency > < groupId >org.webjars</ groupId > < artifactId >jquery</ artifactId > < version >3.4.1</ version > </ dependency > < dependency > < groupId >org.webjars</ groupId > < artifactId >stomp-websocket</ artifactId > < version >2.3.3</ version > </ dependency > < dependency > < groupId >org.webjars</ groupId > < artifactId >webjars-locator-core</ artifactId > </ dependency > |
二、配置 WebSocketConfig
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | @Configuration //开启使用STOMP协议来传输基于代理的消息,Broker就是代理的意思 @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { /** * 配置消息代理 * @param registry */ @Override public void configureMessageBroker(MessageBrokerRegistry registry) { //定义消息代理的前缀 registry.enableSimpleBroker( "/topic" ); //配置一个或者多个前缀,过滤出需要代理方法处理的消息 registry.setApplicationDestinationPrefixes( "/app" ); } /** * 注册STOMP协议的节点,并指定映射的URL * @param registry */ @Override public void registerStompEndpoints(StompEndpointRegistry registry) { //注册STOMP协议节点,同时指定使用 SockJS 协议 registry.addEndpoint( "/chat" ).withSockJS(); } } |
三、配置 Message 类
Message 类用来接收浏览器发送的信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class Message { private String name; private String content; public String getName() { return name; } public void setName(String name) { this .name = name; } public String getContent() { return content; } public void setContent(String content) { this .content = content; } } |
四、配置控制器 GreetingController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @Controller public class GreetingController { /** * 这个方法用来处理浏览器发送来的消息,对其进行处理 * @param message * @return */ //@MessageMapping 类似 @RequestMapping @MessageMapping ( "/hello" ) //处理完之后对其进行转发到 SendTo 中的路径 @SendTo ( "/topic/greetings" ) public Message greeting(Message message) { return message; } } |
这里也可以使用 SimpMessagingTemplate
来进行设置:
1 2 3 4 5 6 7 8 9 | @Controller public class GreetingController { @Autowired SimpMessagingTemplate simpMessagingTemplate; @MessageMapping ( "/hello" ) public void greeting(Message message) { simpMessagingTemplate.convertAndSend( "/topic/greetings" , message); } } |
SimpMessagingTemplate
这个类主要是实现向浏览器发送消息的功能。
五、设置前端页面 chat.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < 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 > </ head > < body > < table > < tr > < td >请输入用户名</ td > < td >< input type = "text" id = "name" ></ td > </ tr > < tr > < td >< input type = "button" id = "connect" value = "连接" ></ td > < td >< input type = "button" id = "disconnect" disabled = "disabled" value = "断开连接" ></ td > </ tr > </ table > < div id = "chat" style = "display: none" > < table > < tr > < td >请输入聊天内容</ td > < td >< input type = "text" id = "content" ></ td > < td >< input type = "button" id = "send" value = "发送" ></ td > </ tr > </ table > < div id = "conversation" >群聊进行中...</ div > </ div > < script > $(function () { $("#connect").click(function () { connect(); }) $("#disconnect").click(function () { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); }) $("#send").click(function () { //将消息发送到代理方法内 stompClient.send('/app/hello',{},JSON.stringify({'name':$("#name").val(),'content':$("#content").val()})) }) }) var stompClient = null; function connect() { if (!$("#name").val()) { return; } //建立连接 var socket = new SockJS('/chat'); stompClient = Stomp.over(socket); //建立连接 stompClient.connect({}, function (success) { setConnected(true); stompClient.subscribe('/topic/greetings', function (msg) { //拿到输入的消息内容进行展示 showGreeting(JSON.parse(msg.body)); }); }) } //展示消息的内容 function showGreeting(msg) { $("#conversation").append('< div >' + msg.name + ':' + msg.content + '</ div >'); } //设置连接按钮,已经连接上则禁止,反之不禁止 function setConnected(flag) { $("#connect").prop("disabled", flag); $("#disconnect").prop("disabled", !flag); //连接上,才显示聊天区的内容 if (flag) { $("#chat").show(); } else { $("#chat").hide(); } } </ script > </ body > </ html > |
六、登录测试
打开两个浏览器,实现群聊功能:
到此这篇关于一篇文章带你使用SpringBoot基于WebSocket的在线群聊实现的文章就介绍到这了,更多相关SpringBoot WebSocket在线群聊内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
![](http://files.jb51.net/skin/2018/images/jb51ewm.png)
微信公众号搜索 “ 脚本之家 ” ,选择关注
程序猿的那些事、送书等活动等着你
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 reterry123@163.com 进行投诉反馈,一经查实,立即处理!
相关文章
java Iterator接口和LIstIterator接口分析
这篇文章主要介绍了java Iterator接口和LIstIterator接口分析的相关资料,需要的朋友可以参考下2017-05-05SpringCloud之服务注册与发现Spring Cloud Eureka实例代码
这篇文章主要介绍了SpringCloud之服务注册与发现Spring Cloud Eureka实例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-04-04
最新评论