<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>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Spring WebSocket 教程 > 原文: [http://zetcode.com/spring/websocket/](http://zetcode.com/spring/websocket/) Spring WebSocket 教程展示了如何在 Spring Web 應用中使用 WebSocket。 Spring 是用于創建企業應用的流行 Java 應用框架。 ## WebSocket WebSocket 是一種計算機通信協議,可通過單個 TCP 連接提供全雙工通信通道。 WebSocket 用于高度互動的應用,例如游戲,聊天或股票市場。 ## TextWebSocketHandler Spring 使用`WebSocketHandler`處理 WebSocket 消息和生命周期事件。 `TextWebSocketHandler`是用于處理文本消息的`WebSocketHandler`實現。 ## Spring `TextWebSocketHandler`示例 以下應用使用`TextWebSocketHandler`通過 WebSocket 處理文本消息。 ```java web.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ ├───config │ │ │ MyWebInitializer.java │ │ │ WebConfig.java │ │ │ WebSocketConfig.java │ │ └───handler │ │ MyWebSocketHandler.java │ ├───resources │ └───webapp │ │ index.html │ └───WEB-INF └───test └───java ``` 這是項目結構。 `pom.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <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.zetcode</groupId> <artifactId>textwebsocketex</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>5.1.2.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> </plugins> </build> </project> ``` 在`pom.xml`文件中,我們具有以下依存關系:`spring-webmvc`,`javax.servlet-api`和`spring-websocket`。 `com/zetcode/config/MyWebInitializer.java` ```java package com.zetcode.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class, WebSocketConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } } ``` `MyWebInitializer`初始化 Spring Web 應用。 它提供了兩個配置類:`WebConfig`和`WebSocket`。 `com/zetcode/config/WebConfig.java` ```java package com.zetcode.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc @ComponentScan("com.zetcode") public class WebConfig implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } } ``` `WebConfig`配置`DefaultServlet`。 在我們的應用中,我們有一個靜態的`index.html`頁面,該頁面由`DefaultServlet`處理。 `com/zetcode/config/WebSocketConfig.java` ```java package com.zetcode.config; import com.zetcode.handler.MyWebSocketHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired private MyWebSocketHandler myWebSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myWebSocketHandler, "/socketHandler"); } } ``` `WebSocketConfig`使用`@EnableWebSocket`在 Spring Web 應用中配置 WebSocket。 ```java @Autowired private MyWebSocketHandler myWebSocketHandler; ``` 我們注入`MyWebSocketHandler`。 已在`registerWebSocketHandlers()`中注冊。 `com/zetcode/config/MyWebSocketHandler.java` ```java package com.zetcode.handler; import org.springframework.stereotype.Component; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.time.LocalTime; @Component public class MyWebSocketHandler extends TextWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { var clientMessage = message.getPayload(); if (clientMessage.startsWith("hello") || clientMessage.startsWith("greet")) { session.sendMessage(new TextMessage("Hello there!")); } else if (clientMessage.startsWith("time")) { var currentTime = LocalTime.now(); session.sendMessage(new TextMessage(currentTime.toString())); } else { session.sendMessage(new TextMessage("Unknown command")); } } } ``` 在`MyWebSocketHandler`中,我們對套接字消息做出反應。 ```java var clientMessage = message.getPayload(); ``` 通過`getPayLoad()`方法,我們獲得了客戶端消息。 ```java if (clientMessage.startsWith("hello") || clientMessage.startsWith("greet")) { session.sendMessage(new TextMessage("Hello there!")); } else if (clientMessage.startsWith("time")) { var currentTime = LocalTime.now(); session.sendMessage(new TextMessage(currentTime.toString())); } else { session.sendMessage(new TextMessage("Unknown command")); } ``` 根據消息,我們將`TextMessage`發送回客戶端。 `webapp/index.html` ```java <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home page</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.css" rel="stylesheet"> </head> <body> <div class="ui container"> <h1>Spring MVC 5 WebSocket</h1> <div class="two column grid"> <div class="row"> <div class="column"> <label for="myMessage">Message</label> </div> <div class="column"> <div class="ui input"> <input type="text" id="myMessage"> </div> </div> </div> <div class="row"> <div class="column"> <label for="output">Response from Server</label> </div> <div class="column"> <textarea rows="8" cols="50" id="output" readonly="readonly"></textarea> </div> </div> <div class="row"> <button class="ui button" onclick="send()">Send</button> </div> </div> </div> <script> const socketConn = new WebSocket('ws://localhost:8080/socketHandler'); function send() { const clientMsg = document.getElementById('myMessage'); if (clientMsg.value) { socketConn.send(clientMsg.value); } } socketConn.onmessage = (e) => { const output = document.getElementById('output'); output.value += `${e.data}\n`; } </script> </body> </html> ``` `index.html`包含應用的客戶端接口。 ```java const socketConn = new WebSocket('ws://localhost:8080/socketHandler'); ``` 在 JavaScript 中,我們創建一個套接字連接。 ```java function send() { const clientMsg = document.getElementById('myMessage'); if (clientMsg.value) { socketConn.send(clientMsg.value); } } ``` 單擊按鈕后,我們將發送帶有`send()`的短信。 ```java socketConn.onmessage = (e) => { const output = document.getElementById('output'); output.value += `${e.data}\n`; } ``` 收到響應后,將調用`onmessage()`事件處理器。 我們獲得響應數據并將其添加到文本區域。 在本教程中,我們創建了一個支持 WebSocket 的簡單 Spring Web 應用。 您可能也對這些相關教程感興趣: [Spring `@GetMapping`教程](/spring/getmapping/), [Spring `DefaultServlet`教程](/spring/defaultservlet/), [Spring Web 應用簡介](/articles/springwebfirst/)和 [Java 教程](/lang/java/)。
                  <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>

                              哎呀哎呀视频在线观看