SpringBoot 搭建简单聊天室
SpringBoot 搭建简单聊天室(queue 点对点)
1、引用 SpringBoot 搭建 WebSocket 链接
https://www.cnblogs.com/yi1036943655/p/10089100.html
2、整合Spring Security
package com.example.demo.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
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { /**
* 简单解释一下
* 页面(login、ws)不设置拦截
* 登录页面login
* 登陆成功页面chat
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/login","/ws").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/chat")
.permitAll()
.and()
.logout()
.permitAll(); } /**
* 添加两个用户
* 账号:wfy 密码:wfy
* 账号:wisely 密码:wisely
* 角色:USER
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(new MyPasswordEncoder())
.withUser("wfy").password("wfy").roles("USER")
.and()
.withUser("wisely").password("wisely").roles("USER");
} /**
* 静态资源路径不设置拦截
* @param web
* @throws Exception
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/static/**");
}
}
3、配置WebSocket
package com.example.demo.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 { /**
* 配置链接端点
* @param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry){
registry.addEndpoint("/endpointWisely").withSockJS();
registry.addEndpoint("/endpointChat").withSockJS();
} /**
* 配置消息代理
* @param registry
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry){
registry.enableSimpleBroker("/topic","/queue");
}
}
4、书写控制器
package com.example.demo.controller; import com.example.demo.PoJo.WiselyMessage;
import com.example.demo.PoJo.WiselyResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller; import java.security.Principal; @Controller
public class WsController { /**
* 服务器 推送数据
*/
@Autowired
private SimpMessagingTemplate messagingTemplate; /**
* MessageMapping 类似于 RequestMapping
* SendTo 订阅地址 类似于 订阅一个URL (我的理解就是 调用了这个方法 在返回的时候会给订阅该url的地址发送数据)
* @param message
* @return
* @throws Exception
*/
@MessageMapping("/welcome")
@SendTo("/topic/getResponse")
public WiselyResponse say(WiselyMessage message) throws Exception {
Thread.sleep(3000);
return new WiselyResponse("Welcome," + message.getName() + "!");
} /**
* 通过convertAndSendToUser 向指定用户发送消息
* @param principal
* @param msg
*/
@MessageMapping("/chat")
public void handleChat(Principal principal,String msg){
if("wfy".equals(principal.getName())){
messagingTemplate.convertAndSendToUser("wisely","queue/notifications",principal.getName() + "-send : "+ msg );
}else{
messagingTemplate.convertAndSendToUser("wfy","queue/notifications",principal.getName() + "-send : "+ msg );
}
} }
5、书写页面(chat)
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8" />
<head>
<title>Home</title>
<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery.js}"></script>
</head>
<body>
<p>
聊天室
</p> <form id="wiselyForm">
<textarea rows="4" cols="60" name="text"></textarea>
<input type="submit"/>
</form> <script th:inline="javascript">
$('#wiselyForm').submit(function(e){
e.preventDefault();
var text = $('#wiselyForm').find('textarea[name="text"]').val();
sendSpittle(text);
}); var sock = new SockJS("/endpointChat"); //1
var stomp = Stomp.over(sock);
stomp.connect('guest', 'guest', function(frame) {
stomp.subscribe("/user/queue/notifications", handleNotification);//2
}); function handleNotification(message) {
$('#output').append("<b>Received: " + message.body + "</b><br/>")
} function sendSpittle(text) {
stomp.send("/chat", {}, text);//3
}
$('#stop').click(function() {sock.close()});
</script> <div id="output"></div>
</body>
</html>
页面(login)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<meta charset="UTF-8" />
<head>
<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>
6、编写视图解析器
package com.example.demo.config; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/ws").setViewName("/ws");
registry.addViewController("/login").setViewName("/login");
registry.addViewController("/chat").setViewName("/chat");
}
}
7、记录一个坑
1)、如果使用的是 Security5.0 以上会报错 java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
解决办法:
package com.example.demo.config;
import org.springframework.security.crypto.password.PasswordEncoder;
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
SpringBoot 搭建简单聊天室的更多相关文章
- Jaguar_websocket结合Flutter搭建简单聊天室
1.定义消息 在开始建立webSocket之前,我们需要定义消息,如:发送人,发送时间,发送人id等.. import 'dart:convert'; class ChatMessageData { ...
- 基于springboot的websocket聊天室
WebSocket入门 1.概述 1.1 Http #http简介 HTTP是一个应用层协议,无状态的,端口号为80.主要的版本有1.0/1.1/2.0. #http1.0/1.1/2.0 1.HTT ...
- ASP.NET SingalR + MongoDB 实现简单聊天室(一):搭建基本框架
ASP.NET SingalR不多介绍.让我介绍不如看官网,我这里就是直接上源代码,当然代码还是写的比较简单的,考虑的也少,希望各位技友多多提意见. 先简单介绍聊天室功能: 用户加入聊天室,自动给用户 ...
- Python Socket 简单聊天室2
上篇文章写了一个简单的单线程的一问一答的简单聊天室.这次我们使用SocketServer模块搭建一个多线程异步的聊天室. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
- 基于Server-Sent Event的简单聊天室 Web 2.0时代,即时通信已经成为必不可少的网站功能,那实现Web即时通信的机制有哪些呢?在这门项目课中我们将一一介绍。最后我们将会实现一个基于Server-Sent Event和Flask简单的在线聊天室。
基于Server-Sent Event的简单聊天室 Web 2.0时代,即时通信已经成为必不可少的网站功能,那实现Web即时通信的机制有哪些呢?在这门项目课中我们将一一介绍.最后我们将会实现一个基于S ...
- SilverLight搭建WCF聊天室详细过程[转]
http://www.silverlightchina.net/html/zhuantixilie/getstart/2011/0424/7148.html 默认节点 SilverLight搭建WCF ...
- Asp.Net SignalR - 简单聊天室实现
简单聊天室 使用持久链接类我们就可以做一些即时通讯的应用了,我使用Group做了一个简单的聊天室,先上图技术细节下面再讲 可以加入聊天室.创建聊天室.发送消息,下面就说说我是如何通过Group做出来的 ...
- 利用socket.io+nodejs打造简单聊天室
代码地址如下:http://www.demodashi.com/demo/11579.html 界面展示: 首先展示demo的结果界面,只是简单消息的发送和接收,包括发送文字和发送图片. ws说明: ...
- C#实例之简单聊天室(状态管理)
前言 状态管理是在同一页或不同页的多个请求发生时,维护状态和页信息的过程.因为Web应用程序的通信协议使用了无状态的HTTP协议,所以当客户端请求页面时,ASP.NET服务器端都会重新生 ...
随机推荐
- NYOJ 2 括号配对问题 (模拟)
题目链接 描述 现在,有一行括号序列,请你检查这行括号是否配对. 输入 第一行输入一个数N(0<N<=100),表示有N组测试数据.后面的N行输入多组输入数据,每组输入数据都是一个字符串S ...
- RMQ之ST求区间最大值
题目链接:https://cn.vjudge.net/problem/HRBUST-1188 每一次按照二进制的方式进行更新,二维数组dp [i] [j],i表示下标,j表示从i 开始的往后移动2的j ...
- Tornado/Python 学习笔记(二)
部分ssrpc.py代码分析 -- 服务端: 1 #!/usr/bin/python3 2 3 from xmlrpc.client import Fault, dumps, loads 4 impo ...
- Cookie、Session 和 自定义分页
cookie Cookie的由来 大家都知道HTTP协议是无状态的. 无状态的意思是每次请求都是独立的,它的执行情况和结果与前面的请求和之后的请求都无直接关系,它不会受前面的请求响应情况直接影响,也不 ...
- Java network programming-guessing game
猜数字游戏 游戏的规则如下: 当客户端第一次连接到服务器端时,服务器端生产一个[0,50]之间的随机数字,然后客户端输入数字来猜该数字,每次客户端输入数字以后,发送给服务器端,服务器端判断该客户端发送 ...
- c++环境配置 Eclipse+mingw-get-setup
1,到官网下载eclipse 和 mingw-get-setup 2,先安装eclipse,然后等着... 3,再安装mingw-get-setup, 等待...安装完成后打开,选择basic s ...
- jquery ajax的再次封装,简化操作
1.封装的ajax var funUrl="" // 每个请求地址相同的部分 function queryData(url,params,success,error){ url ...
- sed的额外用法(网摘)
#在我开始动手写一个一个的脚本的时候才会看到更多的用法 1. 在某行的前一行或后一行添加内容(前提是要确定行的内容) # 匹配行前加 sed -i '/allow/ideny' httpd.conf ...
- linux自动获得mac地址,修改网络配置
1.修改网络配置,自动获得mac地址 删除 /etc/udev/rules.d/70-persistent-net.rules 文件 删除 /etc/sysconfig/network-scripts ...
- fedroa20 没法开启ntpd服务器
1现象:ntpd老是没法开启,ntpd -d显示有个进程占用123端口. [root@vd13crmtb01 ~]# systemctl enable ntpd.service //开 ...