前言
本文主要给大家介绍了关于Spring Boot WebSocket整合及nginx配置的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
一:Spring Boot WebSocket整合
创建一个maven项目,加入如下依赖
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>1.4.0.RELEASE</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> </dependencies>
代码如下:
package com.wh.web; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; public class CountWebSocketHandler extends TextWebSocketHandler { private static long count = 0; protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { session.sendMessage(new TextMessage("你是第" + (++count) + "位访客")); } }
package com.wh.web; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration public class WebsocketConfiguration implements WebSocketConfigurer { public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new CountWebSocketHandler(), "/web/count"); } }
package com.wh.web; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.socket.config.annotation.EnableWebSocket; @EnableWebSocket @SpringBootApplication public class ServerApp { public static void main(String[] args) { SpringApplication.run(ServerApp.class, args); } }
application.properties 内容如下:
server.port=9080 spring.resources.static-locations=classpath:/webapp/html/
src/main/resources/webapp/html/index.html 内容如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>web socket</title> </head> <body> <h1>web socket</h1> <script type="text/javascript"> var url = 'ws://'+window.location.hostname+':9080/web/count'; var ws = new WebSocket(url); ws.onopen = function(event) { ws.send('hello'); }; ws.onmessage = function(event) { alert(event.data); }; ws.onerror = function(event) { alert(event); } </script> </body> </html>