<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Spring Boot WebFlux WebSocket 示例 > 原文: [https://howtodoinjava.com/spring-webflux/reactive-websockets/](https://howtodoinjava.com/spring-webflux/reactive-websockets/) 在這個 spring webflux websocket 示例中,學習使用 [spring webflux](https://howtodoinjava.com/spring-webflux/spring-webflux-tutorial/) 創建支持客戶端和服務器之間的 websocket 連接的響應式應用程序。 [websocket](https://en.wikipedia.org/wiki/WebSocket) 是 Web 瀏覽器和服務器之間的雙向全雙工持久連接。 建立連接后,它將保持打開狀態,直到客戶端或服務器決定關閉此連接。 Websocket 在具有多個用戶相互連接并發送和接收消息的應用程序中具有實際用途,例如聊天應用程序。 ## 1\. Maven 依賴 我們需要具有`spring-boot-starter-webflux`和`javax.websocket-api`依賴項。 > Spring WebFlux 期望使用 WebSockets 版本 **1.1** 。 使用 1.0 時,代碼將無法運行。 `pom.xml` ```java <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.howtodoinjava.demo</groupId> <artifactId>spring-webflux-example</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <name>spring-webflux-example</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> </dependency> </dependencies> </project> ``` ## 2\. `WebSocketHandler` – 消息處理器 在應用程序的中心,我們將有一個[`WebSocketHandler`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/socket/WebSocketHandler.html),它將處理 WebSocket 消息和生命周期事件。 給定的`EchoHandler`將收到一條消息,并以`RECEIVED ON SERVER ::`為前綴返回。 `EchoHandler.java` ```java package com.howtodoinjava.demo.handler; import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.WebSocketSession; import reactor.core.publisher.Mono; public class EchoHandler implements WebSocketHandler { @Override public Mono<Void> handle(WebSocketSession session) { return session .send( session.receive() .map(msg -> "RECEIVED ON SERVER :: " + msg.getPayloadAsText()) .map(session::textMessage) ); } } ``` ## 3\. 配置 WebSocketHandler 首先,需要使用[`SimpleUrlHandlerMapping`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/handler/SimpleUrlHandlerMapping.html)將`WebSocketHandler`映射到 URL。 然后我們需要一個[`WebSocketHandlerAdapter`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/socket/server/support/WebSocketHandlerAdapter.html)來調用`WebSocketHandler`。 最后,為了讓`WebSocketHandlerAdapter`了解傳入的響應式運行時請求,我們需要使用[`ReactorNettyRequestUpgradeStrategy`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/socket/server/upgrade/ReactorNettyRequestUpgradeStrategy.html)配置[`WebSocketService`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/socket/server/WebSocketService.html)(因為我們正在使用默認的 Netty 服務器)。 `EchoApplication.java` ```java package com.howtodoinjava.demo; import java.util.HashMap; import java.util.Map; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.core.Ordered; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.server.WebSocketService; import org.springframework.web.reactive.socket.server.support.HandshakeWebSocketService; import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; import org.springframework.web.reactive.socket.server.upgrade.ReactorNettyRequestUpgradeStrategy; import com.howtodoinjava.demo.handler.EchoHandler; @SpringBootApplication public class EchoApplication { public static void main(String[] args) { SpringApplication.run(EchoApplication.class, args); } @Bean public EchoHandler echoHandler() { return new EchoHandler(); } @Bean public HandlerMapping handlerMapping() { Map<String, WebSocketHandler> map = new HashMap<>(); map.put("/echo", echoHandler()); SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setUrlMap(map); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE); return mapping; } @Bean public WebSocketHandlerAdapter handlerAdapter() { return new WebSocketHandlerAdapter(webSocketService()); } @Bean public WebSocketService webSocketService() { return new HandshakeWebSocketService(new ReactorNettyRequestUpgradeStrategy()); } } ``` ## 4\. Websocket 客戶端 首先創建一個響應式網絡客戶端。 為了在瀏覽器中進行測試,我們有以下兩個文件`app.js`和`index.html`。 JS 文件具有用于連接/斷開連接,發送消息并顯示從服務器接收的消息的代碼。 `app.js` ```java var ws = null; var url = "ws://localhost:8080/echo"; function setConnected(connected) { document.getElementById('connect').disabled = connected; document.getElementById('disconnect').disabled = !connected; document.getElementById('echo').disabled = !connected; } function connect() { ws = new WebSocket(url); ws.onopen = function() { setConnected(true); log('Info: Connection Established.'); }; ws.onmessage = function(event) { log(event.data); }; ws.onclose = function(event) { setConnected(false); log('Info: Closing Connection.'); }; } function disconnect() { if (ws != null) { ws.close(); ws = null; } setConnected(false); } function echo() { if (ws != null) { var message = document.getElementById('message').value; log('Sent to server :: ' + message); ws.send(message); } else { alert('connection not established, please connect.'); } } function log(message) { var console = document.getElementById('logging'); var p = document.createElement('p'); p.appendChild(document.createTextNode(message)); console.appendChild(p); } ``` `index.html` ```java <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/semantic.min.css" /> <script type="text/javascript" src="app.js"></script> </head> <body> <div> <div id="connect-container" class="ui centered grid"> <div class="row"> <button id="connect" onclick="connect();" class="ui green button ">Connect</button> <button id="disconnect" disabled="disabled" onclick="disconnect();" class="ui red button">Disconnect</button> </div> <div class="row"> <textarea id="message" style="width: 350px" class="ui input" placeholder="Message to Echo"></textarea> </div> <div class="row"> <button id="echo" onclick="echo();" disabled="disabled" class="ui button">Echo message</button> </div> </div> <div id="console-container"> <h3>Logging</h3> <div id="logging"></div> </div> </div> </body> </html> ``` ## 5\. 測試 Spring webflux websocket 示例 在瀏覽器中輸入 URL:`http://localhost:8080/index.html` 測試 websocket 的連接,斷開功能,然后嘗試發送一些消息。 ![Spring webflux + websocket example](https://img.kancloud.cn/87/8c/878cfa2ba4b1ff57ab2bdcc8479eaec6_488x410.jpg) Spring webflux + websocket 示例 請問您有關**使用 spring webflux** 與服務器建立響應式 Websocket 連接的問題。 學習愉快! [下載源碼](https://howtodoinjava.com/wp-content/downloads/spring-webflux-websocket.zip)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看