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


分享到:


相關文章: