一. 導(dǎo)入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二. 開啟套接字
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author lhh
*/
@Configuration
public class WebSocketConfig {
/**
* 開啟WebSocket功能
* @return 消息點(diǎn)
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
三. 核心代碼
package com.lhh.demo.im;
import lombok.extern.slf4j.Slf4j;
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.concurrent.ConcurrentHashMap;
@Slf4j
@Component
@ServerEndpoint("/websocket/{id}")
public class WebSocketServer {
/**
* 客戶端ID
*/
private String id = "";
/**
* 與某個(gè)客戶端的連接會(huì)話验烧,需要通過它來給客戶端發(fā)送數(shù)據(jù)
*/
private Session session;
/**
* 記錄當(dāng)前在線連接數(shù)(為保證線程安全琅绅,須對(duì)使用此變量的方法加lock或synchronized)
*/
private static int onlineCount = 0;
/**
* 用來存儲(chǔ)當(dāng)前在線的客戶端(此map線程安全)
*/
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**
* 連接建立成功后調(diào)用
*/
@OnOpen
public void onOpen(@PathParam(value = "id") String id, Session session) {
this.session = session;
// 接收到發(fā)送消息的客戶端編號(hào)
this.id = id;
// 加入map中
webSocketMap.put(id, this);
// 在線數(shù)加1
addOnlineCount();
log.info("客戶端" + id + "加入,當(dāng)前在線數(shù)為:" + getOnlineCount());
try {
sendMessage("WebSocket連接成功");
} catch (IOException e) {
log.error("WebSocket IO異常");
}
}
/**
* 連接關(guān)閉時(shí)調(diào)用
*/
@OnClose
public void onClose() {
// 從map中刪除
webSocketMap.remove(this);
// 在線數(shù)減1
subOnlineCount();
log.info("有一連接關(guān)閉灾杰,當(dāng)前在線數(shù)為:" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用
* @param message 客戶端發(fā)送過來的消息<br/>
* 消息格式:內(nèi)容 - 表示群發(fā)般卑,內(nèi)容|X - 表示發(fā)給id為X的客戶端
* @param session 用戶信息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("來自客戶端的消息:" + message);
String[] messages = message.split("[|]");
try {
if (messages.length > 1) {
sendToUser(messages[0], messages[1]);
} else {
sendToAll(messages[0]);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* 發(fā)生錯(cuò)誤時(shí)回調(diào)
*
* @param session 用戶信息
* @param error 錯(cuò)誤
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("WebSocket發(fā)生錯(cuò)誤");
error.printStackTrace();
}
/**
* 推送信息給指定ID客戶端逢艘,如客戶端不在線哨颂,則返回不在線信息給自己
*
* @param message 客戶端發(fā)來的消息
* @param sendClientId 客戶端ID
*/
public void sendToUser(String message, String sendClientId) throws IOException {
if (webSocketMap.get(sendClientId) != null) {
if (!id.equals(sendClientId)) {
webSocketMap.get(sendClientId)
.sendMessage("客戶端" + id + "發(fā)來消息:" + " <br/> " + message);
} else {
webSocketMap.get(sendClientId).sendMessage(message);
}
} else {
// 如客戶端不在線瓷患,則返回不在線信息給自己
sendToUser("當(dāng)前客戶端不在線", id);
}
}
/**
* 群送發(fā)送信息給所有人
*
* @param message 要發(fā)送的消息
*/
public void sendToAll(String message) throws IOException {
for (String key : webSocketMap.keySet()) {
webSocketMap.get(key).sendMessage(message);
}
}
/**
* 發(fā)送消息
* @param message 要發(fā)送的消息
*/
private void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 獲取在線人數(shù)
* @return 在線人數(shù)
*/
private static synchronized int getOnlineCount() {
return onlineCount;
}
/**
* 有人上線時(shí)在線人數(shù)加一
*/
private static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
/**
* 有人下線時(shí)在線人數(shù)減一
*/
private static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
四. 測(cè)試
以下方法選擇其一即可:
1. 使用websocket測(cè)試網(wǎng)站 http://ws.douqq.com/(推薦純后端使用)
2. 瀏覽器安裝WebSocket Client插件
3. 前端對(duì)接
<!DOCTYPE HTML>
<html>
<head>
<title>WebSocket測(cè)試</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" />
<button onclick="send()">發(fā)送消息</button>
<button onclick="closeWebSocket()">關(guān)閉連接</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
// 判斷當(dāng)前瀏覽器是否支持WebSocket
if('WebSocket' in window){
// 為了方便測(cè)試,故將鏈接寫死
websocket = new WebSocket("ws://localhost:8088/websocket/1");
} else{
alert('Not support websocket')
}
// 連接發(fā)生錯(cuò)誤的回調(diào)方法
websocket.onerror = function(){
setMessageInnerHTML("發(fā)生錯(cuò)誤");
};
// 連接成功建立的回調(diào)方法
websocket.onopen = function(event){
setMessageInnerHTML("打開連接");
}
// 接收到消息的回調(diào)方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
// 連接關(guān)閉的回調(diào)方法
websocket.onclose = function(){
setMessageInnerHTML("關(guān)閉連接");
}
// 監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí)竹祷,主動(dòng)去關(guān)閉websocket連接谈跛,防止連接還沒斷開就關(guān)閉窗口,server端會(huì)拋異常
window.onbeforeunload = function(){
websocket.close();
}
// 將消息顯示在網(wǎng)頁上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
// 關(guān)閉連接
function closeWebSocket(){
websocket.close();
}
// 發(fā)送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>