当前位置:   article > 正文

springboot搭建WebSocket服务端_springboot websocket 搭建

springboot websocket 搭建

基于springboot框架编写一个WebSocket服务端,并通过简单的html界面模拟客户端验证服务端连接。

1、pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.example</groupId>
  6. <artifactId>demo</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>demo</name>
  10. <description>Demo project for Spring Boot</description>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>2.0.4.RELEASE</version>
  15. <relativePath/> <!-- lookup parent from repository -->
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-web</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-test</artifactId>
  30. <scope>test</scope>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-websocket</artifactId>
  39. </dependency>
  40. </dependencies>
  41. <build>
  42. <plugins>
  43. <plugin>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-maven-plugin</artifactId>
  46. </plugin>
  47. </plugins>
  48. </build>
  49. </project>

2、application.yml

  1. spring:
  2. thymeleaf:
  3. prefix: classpath:/templates/

3、Server端代码

3.1、ServerEndpointExporter

首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。

  1. package com.example.demo.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  5. @Configuration
  6. public class WebSocketConfig {
  7. @Bean
  8. public ServerEndpointExporter serverEndpointExporter() {
  9. return new ServerEndpointExporter();
  10. }
  11. }

3.2 WebSocketServer

  1. package com.example.demo.webSocket;
  2. import org.springframework.stereotype.Component;
  3. import javax.websocket.*;
  4. import javax.websocket.server.ServerEndpoint;
  5. @ServerEndpoint("/webSocketServer")
  6. @Component
  7. public class WebSocketDemo {
  8. @OnOpen
  9. public void onOpen(Session session) {
  10. System.out.println("新开启了一个webSocket连接" + session.getId());
  11. }
  12. @OnMessage
  13. public String onMessage(String message, Session session) {
  14. System.out.println("收到客户端发送的信息:"+message);
  15. System.out.println("当前的sessionId:"+session.getId());
  16. return "SUCCESS";
  17. }
  18. @OnClose
  19. public void onClose(Session session, CloseReason reason) {
  20. System.out.println("webSocket连接关闭:sessionId:"+session.getId() + "关闭原因是:"+reason.getReasonPhrase() + "code:"+reason.getCloseCode());
  21. }
  22. @OnError
  23. public void onError(Throwable t) {
  24. t.printStackTrace();
  25. }
  26. }

4、前端html界面

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta name="viewport" content="width=device-width" />
  5. <title>WebSocket 客户端</title>
  6. </head>
  7. <body>
  8. <div>
  9. <input type="button" id="btnConnection" value="连接" />
  10. <input type="button" id="btnClose" value="关闭" />
  11. <input type="button" id="btnSend" value="发送" />
  12. </div>
  13. <script src="/jquery-3.3.1.js" type="text/javascript" charset="utf-8"></script>
  14. <script type="text/javascript">
  15. $(function(){
  16. var socket;
  17. if(typeof(WebSocket) == "undefined") {
  18. alert("您的浏览器不支持WebSocket");
  19. return;
  20. }
  21. $("#btnConnection").click(function() {
  22. //实现化WebSocket对象,指定要连接的服务器地址与端口
  23. socket = new WebSocket("ws://localhost:8080/webSocketServer");
  24. //打开事件
  25. socket.onopen = function() {
  26. alert("Socket 已打开");
  27. //socket.send("这是来自客户端的消息" + location.href + new Date());
  28. };
  29. //获得消息事件
  30. socket.onmessage = function(msg) {
  31. alert(msg.data);
  32. };
  33. //关闭事件
  34. socket.onclose = function() {
  35. alert("Socket已关闭");
  36. };
  37. //发生了错误事件
  38. socket.onerror = function() {
  39. alert("发生了错误");
  40. }
  41. });
  42. //发送消息
  43. $("#btnSend").click(function() {
  44. socket.send("这是来自客户端的消息" + location.href + new Date());
  45. });
  46. //关闭
  47. $("#btnClose").click(function() {
  48. socket.close();
  49. });
  50. });
  51. </script>
  52. </body>
  53. </html>

5、跳转界面代码

  1. package com.example.demo.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. @Controller
  5. public class HelloWorldController {
  6. @GetMapping("/hello")
  7. public String hello() {
  8. return "/webSocketDemo";
  9. }
  10. }

6、目录结构

7、当需要在websocket服务端注入Service或者Dao进行其他的业务逻辑时,常规注入是会产生空指针异常的。

我们需要在websocket中注入applilcationContext对象,从上下文对象中获取。

方法如下:

7.1 先在main方法启动时将application对象注入到webSocket对象中

  1. public static void main(String[] args) {
  2. ConfigurableApplicationContext applicationContext = SpringApplication.run(RangerSocketApplication.class, args);
  3. GatewayWebSocket.setApplicationContext(applicationContext);
  4. }

7.2 在webSocket服务端设置注入方法,并基于上下文进行获取

  1. private static ApplicationContext applicationContext;
  2. public static void setApplicationContext(ApplicationContext context) {
  3. applicationContext = context;
  4. }

7.3 在获取时赋值

  1. private GatewayDao gatewayDao;
  2. if(gatewayDao == null) {
  3. gatewayDao = applicationContext.getBean(GatewayDao.class);
  4. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/892573
推荐阅读
相关标签
  

闽ICP备14008679号