Springboot Web 之个人聊天室的实现

1.引入依赖

这里引入Security、Thymeleaf和Websocket
图片描述

2.配置Security

代码解释:Spring Security 对“/”和“/login”不拦截;
访问路径为“/login”,成功后转向“/chat”;在内存中分配两个用户,角色是“User”;

图片描述

3.配置WebSocket

注册名为/endpointchat的endpoint,增加一个“/queue”的消息代理
图片描述

4.编写Controller

通过SimpMessagingTemplate向浏览器发送消息;在参数中获得princple,principle包含当前用户信息;
这里写死了发送消息的双方;
messagingTemplate.convertAndSendToUser向用户发送消息,第一个参数是接收消息的用户,第二个是浏览器订阅的本身,第三个是消息
图片描述
图片描述

5.login页面

图片描述

6.chat页面

var sock = new SockJS("/endpointChat"); //1
var stomp = Stomp.over(sock);
stomp.connect('guest', 'guest', function(frame) {
    stomp.subscribe("/user/queue/notifications", handleNotification);//2
});

连接“/endpointChat”的endpoint并订阅/user/queue/notifications发送的消息,与Controller中messagingTemplate.convertAndSendToUser订阅地址保持一致,这里多的“/user”是用来指定用户的

图片描述
图片描述
图片描述

7.配置ViewController

图片描述

8.运行

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值