Spring Boot 使用websocket(Spring支持的原生方式)

Spring Boot 使用websocket

1.搭建Spring Boot项目 wsdemo

1.1 pom.xml



    4.0.0

    com.sunlong
    spring-boot-websocket-demo
    1.0.0
    jar

    spring-boot-websocket-demo
    Demo project for Spring Boot

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

    
        UTF-8
        UTF-8
        1.8
    

    

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

        
            org.projectlombok
            lombok
        

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

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

1.2 建立WebSocket接口 MyWebSocket.java

package com.sunlong.websocket;

import com.sunlong.service.SendService;
import com.sunlong.utils.SpringUtil;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * spring-boot-websocket-demo
 *
 * @Author 孙龙
 * @Date 2017/12/4
 */
@ServerEndpoint(value = "/websocket")
@Controller
public class MyWebSocket {

    //静态变量,用来记录当前在线连接数。
    private static int onlineCount = 0;
    //注入Service只能使用这种方式
    private SendService sendService = SpringUtil.getBean(SendService.class);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!ID是" + session.getId() + "    当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {

        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!ID是:" + session.getId() + "   当前在线人数为" + getOnlineCount());
        try {
            session.close();
        } catch (IOException e) {
            System.out.println("关闭资源时出错!");
            e.printStackTrace();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("来自客户端的消息:" + message + "   ID是:" + session.getId());

        sendService.sendMessage(session, "服务器消息!");

    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误》》发生时间:" + System.currentTimeMillis() + "  ID是:" + session.getId());

        error.printStackTrace();
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }

}

1.3发送消息的Service

接口 SendService.java

package com.sunlong.service;

import javax.websocket.Session;
import java.io.IOException;
import java.util.List;

/**
 * spring-boot-websocket-demo
 *
 * @Author 孙龙
 * @Date 2017/11/28
 */
public interface SendService {

    /**
     * 给多个用户发送数据
     *
     * @param sessionList
     * @param message
     * @throws IOException
     */
    void sendBatch(List sessionList, String message) throws IOException;

    /**
     * 发送消息
     *
     * @param session
     * @param message
     * @throws IOException
     */
    void sendMessage(Session session, String message) throws IOException;
}

实现类 SendServiceImpl.java

package com.sunlong.service.impl;

import com.sunlong.service.SendService;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;
import java.util.List;

/**
 * spring-boot-websocket-demo
 *
 * @Author 孙龙
 * @Date 2017/11/28
 */
@Service
public class SendServiceImpl implements SendService {

    @Override
    public void sendBatch(List sessionList, String message) throws IOException {
        for (Session session : sessionList) {
            sendMessage(session, message);
        }
    }

    @Override
    public void sendMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }
}

1.4获取Spring容器Bean的SpringUtil.java

package com.topsec.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    // 获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    // 通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    // 通过class获取Bean.
    public static  T getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }

    // 通过name,以及Clazz返回指定的Bean
    public static  T getBean(String name, Class clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }
}

1.5前端访问页面 ws01.html

在resources/templates目录下




    
    My WebSocket


Welcome

1.6 配置页面映射路径 WebMvcConfig.java

package com.sunlong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * spring-boot-websocket-demo
 * 该类的作用是可以为ws.html提供便捷的地址映射,只需要在地址栏里面输入localhost:8080/ws,就会找到ws.html
 *
 * @Author 孙龙
 * @Date 2017/11/28
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/ws01").setViewName("/ws01");
    }
    

    /**
     * 配置Spring支持的websocket的类,是必须的
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

1.7 端口配置 application.yml

server:
  port: 8585

1.8 启动类WsdemoApplication.java

package com.topsec;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WsdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(WsdemoApplication.class, args);
    }
}

1.9 启动

启动项目,打开浏览器访问http://localhost:8585/ws01 给websocket发送消息,测试是否成功;

Github代码示例
希望能够帮助到你,帮到你请给我一个星星!

你可能感兴趣的:(Spring Boot 使用websocket(Spring支持的原生方式))