Springboot+WebSocket實(shí)現(xiàn)一對(duì)一聊天和公告的示例代碼
1.POM文件導(dǎo)入Springboot整合websocket的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
2.注冊(cè)WebSocket的Bean交給Spring容器管理
@Configuration
public class WebSocketServiceConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.WebSocket服務(wù)端實(shí)現(xiàn)
@ServerEndpoint 注解聲明為一個(gè)WebSocket服務(wù),訪問(wèn)地址為/chat/{username},@Component將其注冊(cè)為Spring的一個(gè)組件,交給Spring進(jìn)行管理
@ServerEndpoint("/chat/{username}")
@Component
@Slf4j
public class WebSocket {
//注入dao或者service,注意:因?yàn)閐ao層接口和service層都是單例的Bean
//webSocket 不是單例的,所以在注入dao或者service時(shí),需要用set方法對(duì)其進(jìn)行注入,保證每一個(gè)都是獨(dú)立的
private static ChatMapper chatMapper;
//參數(shù)中的ChatMapper 是 單例池中的ChatMapper
@Autowired
public void setChatMapper(ChatMapper chatMapperBean){
WebSocket.chatMapper = chatMapperBean;
}
//當(dāng)前連接數(shù)
private static int onLinePersonNum;
//定義為Map結(jié)構(gòu),key值代表用戶名稱或其他唯一標(biāo)識(shí),Value代表對(duì)應(yīng)的WebSocket連接。
//ConcurrentHashMap 保證線程安全,用來(lái)存放每個(gè)客戶端對(duì)應(yīng)的WebSocket對(duì)象
private static Map<String,WebSocket> webSocketMap = new ConcurrentHashMap<String, WebSocket>();
//用戶名
private String username;
//當(dāng)前httpSession
private Session session;
/**
* 打開(kāi)鏈接
* @param username
* @param session
*/
@OnOpen
public void openConnect(@PathParam("username")String username, Session session){
this.session = session;
this.username = username;
//在線連接數(shù)+1
onlinePerNumAdd();
//用戶名和當(dāng)前用戶WebSocket對(duì)象放進(jìn)Map中
webSocketMap.put(this.username,this);
log.info("{}連接服務(wù)器成功。。。。",this.username);
}
/**
* 關(guān)閉連接
* @param username
* @param session
* @PathParam 用來(lái)獲取路徑中的動(dòng)態(tài)參數(shù)Key值
*/
@OnClose
public void closeConnect(@PathParam("username")String username, Session session){
webSocketMap.remove(username);
//在線連接數(shù)-1
onlinePerNumSub();
log.info("{} 斷開(kāi)連接。。。",username);
}
/**
* 錯(cuò)誤提示
*/
@OnError
public void errorConnect(Session session, Throwable error){
log.error("websocket連接異常:{}",error.getMessage());
}
@OnMessage
public void send(String message, Session session) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Map map = objectMapper.readValue(message, Map.class);
sendMessage(map.get("username").toString(),message);
}
/**
* 點(diǎn)對(duì)點(diǎn)發(fā)送
* @param username
* @param message
* @throws IOException
*/
private void sendMessage(String username,String message) throws IOException {
WebSocket webSocket = webSocketMap.get(username);
webSocket.session.getBasicRemote().sendText(message);
}
/**
* 廣播類型發(fā)送
* @param message
* @throws IOException
*/
private void sendMessage(String message) throws IOException {
Set<String> keys = webSocketMap.keySet();
for (String key : keys) {
WebSocket webSocket = webSocketMap.get(key);
webSocket.sendMessage(message);
}
}
private synchronized static void onlinePerNumAdd(){
WebSocket.onLinePersonNum ++;
}
private synchronized static void onlinePerNumSub(){
WebSocket.onLinePersonNum --;
}
private synchronized static int getOnLinePerNum(){
return WebSocket.onLinePersonNum;
}
}
4.webSocket客戶端
chat1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- <script src="https://heerey525.github.io/layui-v2.4.3/layui/layui.js"></script>-->
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<!--<button id="user1" onclick="connect()">連接</button>-->
<input id="link" type="text"/>
<input id="sendMsg" type="text"/>
<button onclick="send()">發(fā)送</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
// function connect() {
//判斷當(dāng)前瀏覽器是否支持WebSocket ,主要此處要更換為自己的地址
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8089/chat/bbb");
}
else{
alert('Not support websocket')
}
//連接發(fā)生錯(cuò)誤的回調(diào)方法
websocket.onerror = function(){
// setMessageInnerHTML("error");
};
//連接成功建立的回調(diào)方法
websocket.onopen = function(event){
console.log("連接成功!??!")
// setMessageInnerHTML("open");
$("#link").val("連接成功!!")
}
//連接關(guān)閉的回調(diào)方法
websocket.onclose = function(){
// setMessageInnerHTML("close");
}
//監(jiān)聽(tīng)窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒(méi)斷開(kāi)就關(guān)閉窗口,server端會(huì)拋異常。
window.onbeforeunload = function(){
websocket.close();
}
//發(fā)送消息
function send(){
websocket.send("aaa");
// onmessage();
}
//接收到消息的回調(diào)方法
// function onmessage(){
websocket.onmessage = function(event){
console.log(event.data)
// setMessageInnerHTML(event.data);
$("#message").append("<h1>"+ event.data + "</h1>")
// }
}
</script>
</html>
chat2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- <script src="https://heerey525.github.io/layui-v2.4.3/layui/layui.js"></script>-->
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<!--<button id="user1" onclick="connect()">連接</button>-->
<input id="link" type="text"/>
<input id="sendMsg" type="text"/>
<button onclick="send()">發(fā)送</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
// function connect() {
//判斷當(dāng)前瀏覽器是否支持WebSocket ,主要此處要更換為自己的地址
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8089/pushMsg/aaa");
}
else{
alert('Not support websocket')
}
//連接發(fā)生錯(cuò)誤的回調(diào)方法
websocket.onerror = function(){
// setMessageInnerHTML("error");
};
//連接成功建立的回調(diào)方法
websocket.onopen = function(event){
console.log("連接成功?。?!")
// setMessageInnerHTML("open");
$("#link").val("服務(wù)器連接成功?。?)
}
//連接關(guān)閉的回調(diào)方法
websocket.onclose = function(){
// setMessageInnerHTML("close");
}
//監(jiān)聽(tīng)窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒(méi)斷開(kāi)就關(guān)閉窗口,server端會(huì)拋異常。
window.onbeforeunload = function(){
websocket.close();
}
//發(fā)送消息
function send(){
websocket.send("bbb");
// onmessage();
}
//接收到消息的回調(diào)方法
// function onmessage(){
websocket.onmessage = function(event){
console.log(event.data)
// setMessageInnerHTML(event.data);
$("#message").append("<h1>"+ event.data + "</h1>")
// }
}
</script>
</html>
以上就是具體的代碼實(shí)現(xiàn),對(duì)于如果用戶離線,websocket斷開(kāi)連接的情況,可以采用持久化的存儲(chǔ)方式。例如使用mysql關(guān)系型數(shù)據(jù)庫(kù)或Redis緩存等等保存用戶的讀取狀態(tài),當(dāng)用戶登錄后查詢用戶是否有未讀消息,然后進(jìn)行推送。
到此這篇關(guān)于Springboot+WebSocket實(shí)現(xiàn)一對(duì)一聊天和公告的示例代碼的文章就介紹到這了,更多相關(guān)Springboot WebSocket一對(duì)一聊天內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot結(jié)合websocket聊天室實(shí)現(xiàn)私聊+群聊
- SpringBoot整合websocket實(shí)現(xiàn)即時(shí)通信聊天
- SpringBoot+WebSocket實(shí)現(xiàn)多人在線聊天案例實(shí)例
- SpringBoot中webSocket實(shí)現(xiàn)即時(shí)聊天
- Springboot基于websocket實(shí)現(xiàn)簡(jiǎn)單在線聊天功能
- SpringBoot+WebSocket搭建簡(jiǎn)單的多人聊天系統(tǒng)
- SpringBoot+Websocket實(shí)現(xiàn)一個(gè)簡(jiǎn)單的網(wǎng)頁(yè)聊天功能代碼
- SpringBoot結(jié)合WebSocket實(shí)現(xiàn)聊天功能
相關(guān)文章
Java中的while無(wú)限循環(huán)結(jié)構(gòu)及實(shí)例
這篇文章主要介紹了Java中的while無(wú)限循環(huán)結(jié)構(gòu)及實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
詳解Elasticsearch如何實(shí)現(xiàn)簡(jiǎn)單的腳本排序
Elasticsearch?是位于?Elastic?Stack?核心的分布式搜索和分析引擎,可以為所有類型的數(shù)據(jù)提供近乎實(shí)時(shí)的搜索和分析。本文主要介紹了Elasticsearch如何實(shí)現(xiàn)簡(jiǎn)單的腳本排序,感興趣的可以了解一下2023-01-01
解決mapper接口無(wú)法映射mapper.xml的問(wèn)題
這篇文章主要介紹了解決mapper接口無(wú)法映射mapper.xml的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Java合并兩個(gè)List后并去掉重復(fù)項(xiàng)的兩種做法
工作中很多時(shí)候需要用到合并兩個(gè)List并去除其中的重復(fù)內(nèi)容,這是一個(gè)很簡(jiǎn)單的操作,實(shí)現(xiàn)的方法也多種多樣,這篇文章主要給大家介紹了關(guān)于Java合并兩個(gè)List后并去掉重復(fù)項(xiàng)的兩種做法,需要的朋友可以參考下2023-10-10
Java給實(shí)體每一個(gè)字段賦默認(rèn)值詳細(xì)代碼示例
這篇文章主要給大家介紹了關(guān)于Java給實(shí)體每一個(gè)字段賦默認(rèn)值的相關(guān)資料,在編程過(guò)程中有時(shí)會(huì)出現(xiàn)這樣一種情況,在查詢無(wú)結(jié)果時(shí)我們需要給實(shí)體賦默認(rèn)值,需要的朋友可以參考下2023-09-09

