SpringBoot中怎么使用WebSocket实现点对点消息
一、添加依赖,配置使用SpringSecurity里的用户。org.springframework.bootspring-boot-starter-security我们现在需要配置用户信息和权限配置。@ConfigurationpublicclassWebSecurityConfigextendsWebSecurityConfigurerAdapter{//指定密码的加密方式@SuppressWarnings("deprecation")@BeanPasswordEncoderpasswordEncode
一、添加依赖,配置
使用 Spring Security 里的用户。
org.springframework.boot spring-boot-starter-security
我们现在需要配置用户信息和权限配置。
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// 指定密码的加密方式
@SuppressWarnings("deprecation")
@Bean
PasswordEncoder passwordEncoder(){
// 不对密码进行加密
return NoOpPasswordEncoder.getInstance();
}
// 配置用户及其对应的角色
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("123").roles("ADMIN","USER")
.and()
.withUser("hangge").password("123").roles("USER");
}
// 配置 URL 访问权限
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() // 开启 HttpSecurity 配置
.anyRequest().authenticated() // 用户访问所有地址都必须登录认证后访问
.and().formLogin().permitAll(); // 开启表单登录
}
}二、编写WebSocket 配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// 设置消息代理的前缀,如果消息的前缀为"/queue",就会将消息转发给消息代理(broker)
// 再由消息代理广播给当前连接的客户端
//也可设置多个 broker,如:config.enableSimpleBroker("/topic","/queue");
config.enableSimpleBroker("/queue");
// 下面方法可以配置一个或多个前缀,通过这些前缀过滤出需要被注解方法处理的消息。
// 例如这里表示前缀为"/app"的destination可以通过@MessageMapping注解的方法处理
// 而其他 destination(例如"/topic""/queue")将被直接交给 broker 处理
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// 定义一个前缀为"/chart"的endpoint,并开启 sockjs 支持。
// sockjs 可以解决浏览器对WebSocket的兼容性问题,客户端将通过这里配置的URL建立WebSocket连接
registry.addEndpoint("/chat").withSockJS();
}
}三、编写案例代码
1、编写实体
@Data
public class Chat {
// 消息的目标用户
private String to;
// 消息的来源用户
private String from;
// 消息的主体内容
private String content;
}2、编写Controller
@Controller
public class DemoController {
@Autowired
SimpMessagingTemplate messagingTemplate;
// 处理来自"/app/chat"路径的消息
@MessageMapping("/chat")
public void chat(Principal principal, Chat chat) {
// 获取当前登录用户的用户名
String from = principal.getName();
// 将用户设置给chat对象的from属性
chat.setFrom(from);
// 再将消息发送出去,发送的目标用户就是 chat 对象的to属性值
messagingTemplate.convertAndSendToUser(chat.getTo(),
"/queue/chat", chat);
}
}四、编写页面
在 resources/static 目录下创建 chat2.html 页面作为点对点的聊天页面。
连接成功后,订阅的地址为“/user/queue/chat”,该地址比服务端配置的地址多了“/user”前缀,这是因为 SimpMessagingTemplate 类中自动添加了路径前缀。
单聊 请输入聊天内容: 目标用户:
五、验证结果
我们使用了 Spring Security 会自动跳转到默认登录页面。

这里我们配置两个用户信息:admin/123,piao/123。


Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















