(二)websocket實現訊息推送之基於spring4.0實現
阿新 • • 發佈:2019-09-20
1、新建springBoot專案,新增依賴
<!--websocket依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2、新建WebConfig類並實現WebSocketConfigurer
@Configuration @EnableWebSocket public class WebConfig implements WebSocketConfigurer { //註冊為服務,暴露介面為【/marco】直接連線這個介面比如: //websocket = new WebSocket('ws://localhost:8088/marco'); @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(marcoHandler(), "/marco") .setAllowedOrigins("*");/*設定為所有訪問,不設定此屬性連線不上*/ } @Bean public MarcoHandler marcoHandler() { return new MarcoHandler(); } }
3、新建MarcoHandler類繼承AbstractWebSocketHandler抽象類
public class MarcoHandler extends AbstractWebSocketHandler { private static final Logger logger = LoggerFactory.getLogger(MarcoHandler.class); private static List<WebSocketSession> list = new ArrayList<>(); //訊息處理 @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { logger.info("Received message: " + message.getPayload()); session.sendMessage(new TextMessage(message.getPayload())); } //連線上觸發 public void afterConnectionEstablished(WebSocketSession session) throws Exception{ list.add(session); System.out.println("connection established"); } //斷開連線觸發 public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception{ list.remove(session); System.out.println("connection closed"); } //傳送訊息方法 public void sendMessage() throws Exception{ for(WebSocketSession webSocketSession:list){ webSocketSession.sendMessage(new TextMessage("哥哥")); } } }
4、編寫html頁面
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>測試</title>
<style>
#message{
height: 520px;
border-bottom: 1px solid gray;
padding: 20px 30px;
}
#container{
margin: 0 auto;
width: 720px;
border: 1px solid gray
}
input{
width: 300px;
height: 36px;
border: 1px solid gray;
background:none;
outline:none;
}
input:focus{
border-color: yellow;
}
button{
height: 36px;
}
</style>
</head>
<body>
<div id="container">
<div id="message">
</div>
<div>
<input id="text" type="text" placeholder="輸入內容..."/>
<button onclick="send()">傳送訊息</button>
</div>
</div>
<script th:inline="javascript" type="text/javascript">
var websocket = null;
//判斷當前瀏覽器是否支援WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket('ws://localhost:8088/marco');
}
else {
alert('當前瀏覽器不支援websocket');
}
//傳送訊息
function send() {
debugger;
var message = document.getElementById('text').value;
websocket.send(message);
}
//接收到訊息的回撥方法
websocket.onmessage = function (event) {
debugger;
var data = event.data;
document.getElementById('message').innerHTML += data+'<br/>';
}
//連線成功建立的回撥方法
websocket.onopen = function () {
console.log("onopen...");
}
//連線關閉的回撥方法
websocket.onclose = function () {
console.log("onclose...");
}
//連線發生錯誤的回撥方法
websocket.onerror = function () {
console.log("onerror...");
};
//監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,server端會拋異常。
window.onbeforeunload = function () {
closeWebSocket();
}
//關閉WebSocket連線
function closeWebSocket() {
websocket.close();
}
</script>
</body>
</html>
6、訪問:
開啟http://127.0.0.1:8088/home.html頁面,然後訪問http://127.0.0.1:8088/indexController/test 連線,home頁面就會收到哥哥這個引數。
我的碼雲地址:https://gitee.com/renting/websocketjiyuspring4