keyholesoftware.com/2017/04/10/…
做者:THOMAS KENDALL
譯者:oopsguy.comhtml
在開發 Web 應用程序時,咱們有時須要將服務端事件推送到鏈接的客戶端。但 HTTP 並不能作到。客戶端打開與服務端的鏈接並請求數據,但服務端不能打開與客戶端的鏈接並推送數據。前端
爲了解決這個限制,咱們能夠創建了一個輪詢模式,網頁會間隔地輪詢服務器以獲取新事件。但這種模式不太理想,由於它增長了 HTTP 開銷,速度也只能達到與輪詢的速率同樣快,而且給服務器增長了沒必要要的負載。html5
幸運的是,HTML5 WebSocket 出現了。WebSocket 協議容許瀏覽器與 Web 服務器之間進行低開銷的交互。在文中,咱們將介紹 Websockets API,並展現如何使用 Spring Boot 實現 Websockets。java
WebSockets 經過瀏覽器和服務器之間的單鏈接提供全雙工通訊。它不存在 HTTP 開銷,而且容許服務器將消息實時推送到客戶端。web
WebSocket API 實際上很簡單。您只須要建立一個 WebSocket
對象,附加事件監聽器和發送消息便可。spring
如下是一個例子:瀏覽器
var socket = new WebSocket('ws://' + window.location.host + '/my-websocket-endpoint');
// Add an event listener for when a connection is open
socket.onopen = function() {
console.log('WebSocket connection opened. Ready to send messages.');
// Send a message to the server
socket.send('Hello, from WebSocket client!');
};
// Add an event listener for when a message is received from the server
socket.onmessage = function(message) {
console.log('Message received from server: ' + message);
};複製代碼
Spring 對 WebSockets 接口提供了很好的支持。前端框架
首先,咱們須要建立一個類,繼承 Spring 的 TextWebSocketHandler
類。服務器
public class MyMessageHandler extends TextWebSocketHandler {
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// The WebSocket has been closed
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// The WebSocket has been opened
// I might save this session object so that I can send messages to it outside of this method
// Let's send the first message
session.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
// A message has been received
System.out.println("Message received: " + textMessage.getPayload());
}
}複製代碼
接下來,咱們須要配置 WebSocket 端點。websocket
@Configuration
@EnableWebSocket
public class WebsocketConfig implements WebSocketConfigurer {
@Bean
public WebSocketHandler myMessageHandler() {
return new MyMessageHandler();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myMessageHandler(), "/my-websocket-endpoint");
}
}複製代碼
因爲 WebSockets API 是純 JavaScript,您能夠在大多數前端框架中它。包括 Angular,您能夠在 TypeScript 中包含 JavaScript 代碼。
是否是至關簡單?它解決了服務端和客戶端之間傳輸數據的一大困擾。Spring Boot 使它變得更加簡單。