springboot搭建WebSocket服务端

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

1、pom.xml



    4.0.0

    com.example
    demo
    0.0.1-SNAPSHOT
    jar

    demo
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

        
            org.springframework.boot
            spring-boot-starter-websocket
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

2、application.yml

spring:
  thymeleaf:
    prefix: classpath:/templates/

3、Server端代码

3.1、ServerEndpointExporter

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

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

3.2 WebSocketServer

package com.example.demo.webSocket;


import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/webSocketServer")
@Component
public class WebSocketDemo {


    @OnOpen
    public void onOpen(Session session) {
        System.out.println("新开启了一个webSocket连接" + session.getId());
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        System.out.println("收到客户端发送的信息:"+message);
        System.out.println("当前的sessionId:"+session.getId());
        return "SUCCESS";
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        System.out.println("webSocket连接关闭:sessionId:"+session.getId() + "关闭原因是:"+reason.getReasonPhrase() + "code:"+reason.getCloseCode());
    }


    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }

}

4、前端html界面





    
    WebSocket 客户端



5、跳转界面代码

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloWorldController {
    @GetMapping("/hello")
    public String hello() {
        return "/webSocketDemo";
    }
}

6、目录结构

springboot搭建WebSocket服务端_第1张图片

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

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

方法如下:

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

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

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

private static ApplicationContext applicationContext;

public static void setApplicationContext(ApplicationContext context) {
    applicationContext = context;
}

7.3 在获取时赋值

private GatewayDao gatewayDao;

if(gatewayDao == null) {
    gatewayDao = applicationContext.getBean(GatewayDao.class);
}

 

你可能感兴趣的:(javaWeb)