1、配置pom.xml
<!-- 增加 websocket--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2、編寫websocket配置類
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter;.
@Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } @Bean public WebSocketEndpointConfigure newConfigure() { return new WebSocketEndpointConfigure(); } }
3、編寫 WebSocketEndpoint配置類
import javax.websocket.server.ServerEndpointConfig; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware;
public class WebSocketEndpointConfigure extends ServerEndpointConfig.Configurator implements ApplicationContextAware { private static volatile BeanFactory context; @Override public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException { return context.getBean(clazz); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { WebSocketEndpointConfigure.context = applicationContext; } }
4、編寫WebSocketServer
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;
@Component @ServerEndpoint(value = "/webSocket/{userId}", configurator = WebSocketEndpointConfigure.class) public class WebSocketServer { // ConcurrentHashMap用來存放每個客戶端對應的WebSocketServer對象。 private static ConcurrentHashMap<String,Session> webSocketSet = new ConcurrentHashMap<String, Session>(); private Logger log = LoggerFactory.getLogger(WebSocketServer.class); /** * 連接建立成功調用的方法 */ @OnOpen public void onOpen(Session session,@PathParam("userId") String userId) { webSocketSet.put(userId,session); //相關業務處理,根據拿到的用戶ID判斷其爲那種角色,根據角色ID去查詢是否有需要推送給該角色的消息,有則推送 List<String> totalPushMsgs = new ArrayList<String>(); totalPushMsgs.add("歡迎您:"+ userId); if(totalPushMsgs != null && !totalPushMsgs.isEmpty()) { totalPushMsgs.forEach(e -> sendMessage(userId,e)); } } public void sendMessage(String userId,String message) { try { Session currentSession = webSocketSet.get(userId); if(currentSession != null){ currentSession.getBasicRemote().sendText(message); } log.info("推送消息成功,消息爲:" + message); } catch (IOException e) { log.error(e.getMessage()); } } /** * 自定義消息 */ public static void sendInfo(String userId,String message) throws IOException { Session currentSession = webSocketSet.get(userId); if(currentSession != null){ currentSession.getBasicRemote().sendText(message); } } /** * 用戶退出時,連接關閉調用的方法 */ public static void onCloseConection(String userId) { webSocketSet.remove(userId); // 從set中刪除 } /** * 連接關閉調用的方法 */ @OnClose public void onClose() { log.info("一個客戶端關閉連接"); } /** * 收到客戶端消息後調用的方法 * @param message * 客戶端發送過來的消息 */ @OnMessage public void onMessage(String message, Session session) { } /** * 發生錯誤時調用 */ @OnError public void onError(Session session, Throwable error) { log.error("websocket出現錯誤"); } }
5、編寫前端代碼
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判斷當前瀏覽器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8761/webSocket/111");
}
else{
alert('Not support websocket')
}
//連接發生錯誤的回調方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//連接成功建立的回調方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回調方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//連接關閉的回調方法
websocket.onclose = function(){
setMessageInnerHTML("close");
}
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function(){
websocket.close();
}
//將消息顯示在網頁上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關閉連接
function closeWebSocket(){
websocket.close();
}
//發送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
6、java後臺只需要
WebSocketServer.sendInfo(userId,"我是後臺消息");
消息會發送到 websocket.onmessage方法上