SpringBoot快速集成WebSocket實現群聊
- 添加pom依賴
<!-- springboot websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- java
package cn.pconline.pcloud.admin.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @Description WebSocket配置
* @Author jie.zhao
* @Date 2020/3/23 18:32
*/
@Configuration
public class WebSocketConfig {
//實例化一個Bean對象
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package cn.pconline.pcloud.admin.controller.api;
import cn.pconline.framework.enums.MessageTypeEnum;
import cn.pconline.pcloud.base.dto.MessageDto;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Description 群聊websocket
* @Author jie.zhao
* @Date 2020/3/23 18:34
*/
@Component
@ServerEndpoint("/groupChat/{groupNo}/{name}")
public class GroupChatWebsocket {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 保存 組id->組成員 的映射關系
* 之所以使用ConcurrentHashMap因為這個是線程安全的
*/
private static ConcurrentHashMap<String, List<Session>> groupMemberInfoMap = new ConcurrentHashMap<>();
/**
* 收到消息調用的方法,群成員發送消息
*
* @param groupNo
* @param name
* @param message
*/
@OnMessage
public void onMessage(@PathParam("groupNo") String groupNo,
@PathParam("name") String name, String message) {
//得到當前群的所有會話,也就是所有用戶
List<Session> sessionList = groupMemberInfoMap.get(groupNo);
MessageDto dto = new MessageDto();
dto.setType(MessageTypeEnum.CHAT.getType());
dto.setOnlineNum(sessionList.size());
// 遍歷Session集合給每個會話發送文本消息
sessionList.forEach(item -> {
try {
dto.setName(name);
dto.setContent(message);
item.getBasicRemote().sendText(JSON.toJSONString(dto));
} catch (IOException e) {
e.printStackTrace();
}
});
}
/**
* 建立連接調用的方法,群成員加入
*
* @param session 會話
* @param groupNo 群id
*/
@OnOpen
public void onOpen(Session session, @PathParam("groupNo") String groupNo) {
//得到當前群的所有會話,也就是所有用戶
List<Session> sessionList = groupMemberInfoMap.get(groupNo);
if (sessionList == null) {
sessionList = new ArrayList<>();
groupMemberInfoMap.put(groupNo, sessionList);
}
sessionList.add(session);
logger.info("連接建立");
logger.info("直播房間號: {}, 直播在線人數: {}", groupNo, sessionList.size());
systemOnlineNumMsg(sessionList, sessionList.size());
}
/**
* 關閉連接調用的方法,群成員退出
*
* @param session
* @param groupNo
*/
@OnClose
public void onClose(Session session, @PathParam("groupNo") String groupNo) {
List<Session> sessionList = groupMemberInfoMap.get(groupNo);
sessionList.remove(session);
logger.info("連接關閉");
logger.info("直播房間號: {}, 直播在線人數: {}", groupNo, sessionList.size());
systemOnlineNumMsg(sessionList, sessionList.size());
}
/**
* 傳輸消息錯誤調用的方法
*
* @param error
*/
@OnError
public void OnError(Throwable error) {
logger.info("連接出錯:{}", error.getMessage());
}
/**
* 在線人數系統通知
* @param sessionList
* @param onlineNum
*/
public void systemOnlineNumMsg(List<Session> sessionList , int onlineNum) {
// 遍歷Session集合給每個會話發送文本消息
MessageDto dto = new MessageDto();
dto.setType(MessageTypeEnum.SYSTEM.getType());
sessionList.forEach(item -> {
try {
dto.setOnlineNum(onlineNum);
item.getBasicRemote().sendText(JSON.toJSONString(dto));
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
package cn.pconline.pcloud.admin.controller.api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Description 測試
* @Author jie.zhao
* @Date 2020/3/23 18:41
*/
@Controller
@RequestMapping("/api")
public class TestChatController {
@RequestMapping("/test")
public String index(){
return "api/test";
}
}
- 測試html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>直播互動</title>
<!--適應移動端-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--css樣式-->
<style>
body{ margin:0 auto; width:400px; border:1px solid #F00}
.box{margin:20px;}
</style>
<!--引用jquery庫-->
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>
<body>
<div class="box">
<p>直播房間號</p>
<input type="text" id="groupNo" value="1585023517289" placeholder="請輸入房間號"/>
<p>昵稱</p>
<input type="text" id="name" value="" placeholder="請輸入昵稱"/>
<p>聊天內容</p>
<textarea rows="3" cols="20" id="content" placeholder="請輸入聊天內容"></textarea> <br/>
<input type="submit" value="發送" onclick="start()"/>
<p>-----------------------------------------</p>
<div id="messages" style=""></div>
</div>
<script type="text/javascript">
var webSocket = null;
//收到消息
function onMessage(event) {
$('#messages').append('<p>'+ event.data+'</p>');
}
//建立連接
function onOpen(event) {
console.log('連接已經建立');
}
//發生錯誤
function onError(event) {
console.log('發生錯誤');
webSocket = null;
}
//連接關閉
function onClose(event) {
console.log('連接關閉');
webSocket = null;
}
//連接
function connect() {
//獲取群號
var groupNo = $('#groupNo').val();
//獲取昵稱
var name = $('#name').val();
//驗證非法數據
if (url == '' || name == '') {
alert('群號和用戶名不能為空');
return;
}
//驗證是否已經建立連接
if (webSocket != null) {
alert('已經建立過連接,如需重新建立連接,請自行更改邏輯,或者重新刷新頁面');
return;
}
//創建Websocket連接url
var url = 'ws://127.0.0.1:8080/cisco/groupChat/' + groupNo + '/' + name;
//實例化WebSocket
try {
webSocket = new WebSocket(url);
}catch(err){
}
//出現錯誤
webSocket.onerror = function (event) {
onError(event)
};
//調用創建連接
webSocket.onopen = function (event) {
onOpen(event)
};
//調用收到消息
webSocket.onmessage = function (event) {
onMessage(event)
};
//調用關閉連接
webSocket.onclose = function (event) {
onClose(event)
};
}
//開始發送
function start() {
//獲取發送的內容
var text = $('#content').val();
if (text == '') {
alert('發送內容不允許為空');
return;
}
if (webSocket == null) {
console.log('連接已關閉,正在重新連接');
connect();
}
//調用WebSocket發送的方法
webSocket.send(text);
//初始化文本域的內容為空
$('#content').val('')
}
//連接檢測,重試連接
function wsCheck() {
setTimeout(function () {
if (webSocket == null) {
connect();
console.log('連接健康監測:'+(webSocket!=null?'ok':'error'));
}
wsCheck();
}, 1000 * 10);
}
window.onload = function(){
var name = $.cookie('cisco-cookie-name');
if(name==null||name==''){
name = '游客'+ Date.parse(new Date());
$.cookie('cisco-cookie-name', name, { expires: 7 });
}
$('#name').val(name)
connect();
wsCheck();
}
</script>
</body>
</html>
