1.引入websocket依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<scope>provided</scope>
</dependency>
2.添加配置文件WebSocketConfig.class
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.實(shí)現(xiàn)消息通知類WebSocketServer.class
@Component
@ServerEndpoint(value = "/websocket/{id}")
public class WebSocketServer {
private static int onlineCount = 0;
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
//與某個(gè)客戶端的連接會(huì)話,需要通過它來(lái)給客戶端發(fā)送數(shù)據(jù)
private Session session;
private static Logger log = LogManager.getLogger(WebSocketServer.class);
private String id = "";
/**
* 連接建立成功調(diào)用的方法
* @param id 用戶的標(biāo)識(shí)
* @param session 會(huì)話
*/
@OnOpen
public void onOpen(@PathParam(value = "id") String id, Session session) {
//設(shè)置超時(shí)時(shí)間
session.setMaxIdleTimeout(3600000);
this.session = session;
//接收到發(fā)送消息的人員編號(hào)
this.id = id;
//加入set中
if (webSocketMap.containsKey(id)){
webSocketMap.remove(id);
}
webSocketMap.put(id, this);
//在線數(shù)加1
addOnlineCount();
log.info("用戶"+id+"加入缕粹!當(dāng)前在線人數(shù)為" + getOnlineCount());
try {
sendMessage("連接成功");
} catch (IOException e) {
log.error("websocket IO異常");
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
//從map中刪除
webSocketMap.remove(this.id);
//在線數(shù)減1
subOnlineCount();
log.info("有一連接關(guān)閉叉弦!當(dāng)前在線人數(shù)為" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
* @param message 客戶端發(fā)送過來(lái)的消息
* @param session 會(huì)話
* */
@OnMessage
public void onMessage(String message, Session session) {
log.info("來(lái)自客戶端的消息:" + message);
//可以自己約定字符串內(nèi)容耕漱,比如 內(nèi)容|0 表示信息群發(fā)潜慎,內(nèi)容|X 表示信息發(fā)給id為X的用戶
String sendMessage = message.split("[|]")[0];
String sendUserId = message.split("[|]")[1];
try {
if(sendUserId.equals("0")) {
sendtoAll(sendMessage);
}
else {
sendMessageTo(sendMessage, sendUserId);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("發(fā)生錯(cuò)誤");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public void sendMessageTo(String message,String sendUserId) throws IOException{
if (webSocketMap.get(sendUserId) != null) {
if(!id.equals(sendUserId)){
webSocketMap.get(sendUserId).sendMessage( "用戶" + id + "發(fā)來(lái)消息:" + " <br/> " + message);
}
else {
webSocketMap.get(sendUserId).sendMessage(message);
}
} else {
//如果用戶不在線則返回不在線信息給自己
// sendtoUser("當(dāng)前用戶不在線",id);
}
}
/**
* 發(fā)送信息給所有人
* @param message
* @throws IOException
*/
public void sendtoAll(String message) throws IOException {
for (String key : webSocketMap.keySet()) {
try {
webSocketMap.get(key).sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
4.測(cè)試
前端js訪問http://localhost:8080/websocket/123