SpringBoot中WebSocket的应用:即时通讯
来源:互联网 发布:耳机煲机软件 编辑:程序博客网 时间:2024/05/16 11:31
1.新建一个springboot工程,添加websocket、Thymleaf,Security依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <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>
2.配置WebSocket
package com.cvsea.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@EnableWebSocketMessageBrokerpublic class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{ @Override public void registerStompEndpoints(StompEndpointRegistry P_Registry) { P_Registry.addEndpoint("/endpointChat").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry P_Registry) { P_Registry.enableSimpleBroker("/queue"); }}
3.配置SpringSecurity
package com.cvsea.config;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.builders.WebSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/", "/login").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login") .defaultSuccessUrl("/chat").permitAll().and().logout().permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("pxs").password("123456").roles("USER").and().withUser("lgp").password("123456").roles("USER"); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/static/**"); }}
4.配置WebMVC
package com.cvsea.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter{ @Override public void addViewControllers(ViewControllerRegistry P_Registry) { P_Registry.addViewController("/login").setViewName("/login"); P_Registry.addViewController("/chat").setViewName("/chat"); }}
5.前端控制器
package com.cvsea.contoller;import java.security.Principal;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.messaging.handler.annotation.MessageMapping;import org.springframework.messaging.simp.SimpMessagingTemplate;import org.springframework.stereotype.Controller;@Controllerpublic class ChatContoller { @Autowired private SimpMessagingTemplate messagingTemplate; @MessageMapping("/chat") public void handleChat(Principal P_Principal,String msg) { String strSendTo=P_Principal.getName().equals("pxs")?"lgp":"pxs"; System.out.println("strSendTo:"+strSendTo); messagingTemplate.convertAndSendToUser(strSendTo, "/queue/notifications", P_Principal.getName()+"-Send:"+msg); }}
6.登录
/src/main/resources/templates/login.html
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"/><title>登录</title></head><body> <div th:if="${param.error}">无效的账号和密码</div> <div th:if="${param.logout}">你已注销</div><form th:action="@{/login}" method="post"> <div><label>账号:<input type="text" name="username"/></label></div> <div><label>密码:<input type="password" name="password"/></label></div> <div><input type="submit" value="登录"/></div></form></body></html>
7.聊天主界面
/src/main/resources/templates/chat.html
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8" /><title>即时通讯</title><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></head><body> <h2>即时通讯</h2> <form id="cvseaForm"> <textarea rows="4" cols="60" name="text" id="content"></textarea> <input type="submit" value="发送" /> </form> <input type="button" value="断开连接" id="stop" /> <ul id="response"></ul> <script th:inline="javascript"> var sock = new SockJS("endpointChat"); var stomp = Stomp.over(sock); stomp.connect("guest", "guest", function(frame) { stomp.subscribe("/user/queue/notifications", handleNotification); }); $("#cvseaForm").submit(function(e) { e.preventDefault(); var content = $("#content").val(); sendSpittle(content); }); function handleNotification(message) { $("#response").append("<li>Re:" + message.body + "</li>"); } function sendSpittle(message) { stomp.send("/chat", {}, message); } $("#stop").click(function() { sock.close(); }); </script></body></html>
8.添加js脚本到/src/main/resources/static/
#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/
9.运行测试
- 登录
- 聊天
阅读全文
0 0
- SpringBoot中WebSocket的应用:即时通讯
- springboot中websocket的简单应用
- SpringBoot中WebSocket的应用:聊天室
- SpringBoot中WebSocket不能实现注入的问题
- 基于WebSocket的网页端即时通讯技术
- 基于WebSocket的网页端即时通讯
- javaWEB项目中webSocket的简单应用
- 即时通讯系统的应用
- 即时通讯系统的应用
- 即时通讯的应用
- springboot websocket
- SpringBoot-Websocket
- SpringBoot + WebSocket
- SpringBoot学习-(十二)SpringBoot中建立WebSocket连接
- WCF中WindowsMobileMailBinding的应用-Mobile中的即时通讯应用程序
- 互联网即时通讯中IP组播技术的应用
- SpringBoot中Servlet&Listener&Filter的应用
- 即时聊天,websocket,即时通讯
- 解决win10或win8“你的电脑已脱机。请使用上次在此电脑上使用的密码登录”的问题
- SVN使用:用TortoiseSVN查看Log 无法显示最新的版本和Log信息问题
- Error1error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartupLI
- 7.MongoDB与python交互
- Python学习多进程并发写入同一文件
- SpringBoot中WebSocket的应用:即时通讯
- 基于Qt的OpenGL点云显示基本框架
- (测试成功!)MacBookPro2017下安装MyEclipse2017CI8并破解注册成功!
- ubuntu system settings 打不开
- 贪心算法的找零问题
- App开发团队必须知道的 iOS 11 更新点
- 8.账户管理(非数据库管理人员理解篇
- c语言变量初始化
- CC2640R2F之基础--工程管理篇(下)--外设驱动IO口分配(纯干货)