SpringBoot+Vue+WebSocket 实现在线聊天

一、前言

本文将基于 SpringBoot + Vue + WebSocket 实现一个简单的在线聊天功能

页面如下:

SpringBoot+Vue+WebSocket 实现在线聊天

在线体验地址:http://www.zhengqingya.com:8101

二、SpringBoot + Vue + WebSocket 实现在线聊天

1、引入websocket依赖


org.springframework.boot
spring-boot-starter-websocket

2、websocket 配置类

@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

3、websocket 处理类Controller

@Slf4j
@Component
@ServerEndpoint("/groupChat/{sid}/{userId}")
public class WebSocketServerController {

/**
* 房间号 -> 组成员信息
*/
private static ConcurrentHashMap> groupMemberInfoMap = new ConcurrentHashMap<>();

/**
* 房间号 -> 在线人数
*/
private static ConcurrentHashMap> onlineUserMap = new ConcurrentHashMap<>();

/**
* 收到消息调用的方法,群成员发送消息
*
* @param sid:房间号
* @param userId:用户id
* @param message:发送消息
*/
@OnMessage
public void onMessage(@PathParam("sid") String sid, @PathParam("userId") Integer userId, String message) {
List sessionList = groupMemberInfoMap.get(sid);
Set onlineUserList = onlineUserMap.get(sid);
// 先一个群组内的成员发送消息
sessionList.forEach(item -> {
try {
// json字符串转对象
MsgVO msg = JSONObject.parseObject(message, MsgVO.class);
msg.setCount(onlineUserList.size());
// json对象转字符串
String text = JSONObject.toJSONString(msg);
item.getBasicRemote().sendText(text);
} catch (IOException e) {
e.printStackTrace();
}
});
}

/**
* 建立连接调用的方法,群成员加入
*
* @param session
* @param sid
*/
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid, @PathParam("userId") Integer userId) {
List
sessionList = groupMemberInfoMap.computeIfAbsent(sid, k -> new ArrayList<>());
Set onlineUserList = onlineUserMap.computeIfAbsent(sid, k -> new HashSet<>());
onlineUserList.add(userId);
sessionList.add(session);
// 发送上线通知
sendInfo(sid, userId, onlineUserList.size(), "上线了~");
}


public void sendInfo(String sid, Integer userId, Integer onlineSum, String info) {
// 获取该连接用户信息
User currentUser = ApplicationContextUtil.getApplicationContext().getBean(UserMapper.class).selectById(userId);
// 发送通知
MsgVO msg = new MsgVO();
msg.setCount(onlineSum);
msg.setUserId(userId);
msg.setAvatar(currentUser.getAvatar());
msg.setMsg(currentUser.getNickName() + info);
// json对象转字符串
String text = JSONObject.toJSONString(msg);
onMessage(sid, userId, text);
}

/**
* 关闭连接调用的方法,群成员退出
*
* @param session
* @param sid
*/
@OnClose
public void onClose(Session session, @PathParam("sid") String sid, @PathParam("userId") Integer userId) {
List sessionList = groupMemberInfoMap.get(sid);
sessionList.remove(session);
Set onlineUserList = onlineUserMap.get(sid);
onlineUserList.remove(userId);
// 发送离线通知
sendInfo(sid, userId, onlineUserList.size(), "下线了~");
}

/**
* 传输消息错误调用的方法

*
* @param error
*/
@OnError
public void OnError(Throwable error) {
log.info("Connection error");
}
}

4、websocket 消息显示类

@Data
@ApiModel(description = "websocket消息内容")
public class MsgVO {

@ApiModelProperty(value = "用户id")
private Integer userId;

@ApiModelProperty(value = "用户名")
private String username;

@ApiModelProperty(value = "用户头像")
private String avatar;

@ApiModelProperty(value = "消息")
private String msg;

@ApiModelProperty(value = "在线人数")
private int count;

}

5、前端页面

温馨小提示:当用户登录成功之后,可以发起websocket连接,存在store中...

下面只是单页面的简单实现





本文案例demo源码

https://gitee.com/zhengqingya/xiao-xiao-su


分享到:


相關文章: