javascript
实时通信:使用Spring Boot实现Websocket
在開發Web應用程序時,有時我們需要將服務器事件下推到已連接的客戶端。 但是,HTTP并非旨在允許這樣做。 客戶端打開與服務器的連接并請求數據。 服務器不會打開與客戶端的連接并推送數據。
為了解決此限制,建立了一種輪詢模式,其中網頁將間歇地輪詢服務器是否有任何新事件。 這種模式不理想,因為它增加了HTTP開銷,僅與輪詢速率一樣快,并在服務器上造成了不必要的負載。
幸運的是,隨著HTML5的出現,WebSocket出現了。 WebSocket協議使瀏覽器和Web服務器之間的交互具有較低的開銷。 在此博客中,我們將介紹Websockets API并展示如何使用Spring Boot實現Websockets。
搶救HTML5!
WebSocket通過瀏覽器和服務器之間的單個連接提供全雙工通信。 它沒有HTTP的開銷,并允許服務器將消息實時推送到客戶端。
WebSocket API實際上非常簡單。 創建一個WebSocket對象,附加事件偵聽器,并發送消息。
這是一個例子:
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 serversocket.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靴
Spring對與WebSockets的接口提供了出色的支持。
首先,我們需要創建一個擴展Spring類TextWebSocketHandler類。
public class MyMessageHandler extends TextWebSocketHandler {@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {// The WebSocket has been closed}@Overridepublic 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 messagesession.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));}@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {// A message has been receivedSystem.out.println("Message received: " + textMessage.getPayload());} }接下來,我們需要配置WebSocket端點。
@Configuration @EnableWebSocket public class WebsocketConfig implements WebSocketConfigurer {@Beanpublic WebSocketHandler myMessageHandler() {return new MyMessageHandler();}@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(myMessageHandler(), "/my-websocket-endpoint");}}由于WebSockets API是純JavaScript,因此您應該能夠在大多數前端框架中使用它。 這包括Angular,因為您可以在TypeScript中直接包含JavaScript。
最后的想法
非常簡單,它解決了服務器和客戶端之間同時進行數據傳輸的麻煩。 Spring Boot使它變得更加容易。
想要看Websockets的實際應用嗎? 在Keyhole,我們構建了一個開源工具Trouble Maker ,該工具將故障注入到我們的平臺中,以便我們可以練習和測試使平臺具有彈性的恢復機制。 Trouble Maker具有Angular前端,并利用WebSocket進行一些實時通信。 查看Github Repo嘗試一下。
翻譯自: https://www.javacodegeeks.com/2017/04/real-time-communication-implementing-websockets-spring-boot.html
總結
以上是生活随笔為你收集整理的实时通信:使用Spring Boot实现Websocket的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 路由器的口应该怎么接如何接路由器端口
- 下一篇: 使用Spring Cloud Confi