一、添加WebSocketConfig配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 開啟WebSocketConfig
* @author: xuyanqi
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
二、創建WebSocket服務處理類
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSONObject;
import com.elephant.framework.galaxy.travel.response.R;
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.CopyOnWriteArraySet;
/**
* 服務處理類
* @author: xuyanqi
*/
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
static Log log = LogFactory.get(WebSocketServer.class);
//靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
//concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//與某個客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
//接收sid 用了標識哪個模塊的通信
private String sid="";
/**
* 連接建立成功調用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數加1
log.info("有新窗口開始監聽:"+sid+",當前在線人數為" + getOnlineCount());
this.sid=sid;
try {
sendMessage("連接成功");
} catch (IOException e) {
log.error("websocket IO異常");
e.printStackTrace();
}
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數減1
log.info("有一連接關閉!當前在線人數為" + getOnlineCount());
}
/**
* 收到客戶端消息后調用的方法
*
* @param message 客戶端發送過來的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到來自窗口"+sid+"的信息:"+message);
//群發消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("發生錯誤");
error.printStackTrace();
}
/**
* 實現服務器主動推送
*/
public void sendMessage(Object obj) throws IOException {
R r = new R(obj);
this.session.getBasicRemote().sendText(JSONObject.toJSONString(r));
}
/**
* 群發自定義消息
* */
public static void sendInfo(Object obj,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送內容:"+obj);
for (WebSocketServer item : webSocketSet) {
try {
//這里可以設定只推送給這個sid的,為null則全部推送
if(sid==null) {
item.sendMessage(obj);
}else if(item.sid.equals(sid)){
item.sendMessage(obj);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
三、vue前端
在data中創建websock對象
/**
* 創建websocket
*/
initWebSocket(){
console.log("創建WebSocket")
this.websock = new WebSocket("ws://127.0.0.1:9998/websocket/ydsj")
this.websock.onmessage = this.websocketonmessage
this.websock.onerror = this.websocketonerror
this.websock.onopen = this.websocketonopen
this.websock.onclose = this.websocketclose
},
// 連接建立之后執行send方法發送數據
websocketonopen () {
let data = {
code: 0,
msg: '這是client:初次連接'
}
this.websocketsend(data)
},
websocketonerror () {
console.log( 'WebSocket連接失敗')
},
// 數據接收
websocketonmessage (e) {
console.log('數據接收' + e.data)
},
// 數據發送
websocketsend (Data) {
this.websock.send(Data)
},
// 關閉
websocketclose (e) {
console.log('已關閉連接', e)
}