美文网首页Springboot来到JavaEESpringHome
Spring Boot 使用websocket(Spring支持

Spring Boot 使用websocket(Spring支持

作者: 搁浅_Jay | 来源:发表于2018-07-12 21:54 被阅读132次

    Spring Boot 使用websocket

    1.搭建Spring Boot项目 wsdemo

    1.1 pom.xml

    <?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.sunlong</groupId>
        <artifactId>spring-boot-websocket-demo</artifactId>
        <version>1.0.0</version>
        <packaging>jar</packaging>
    
        <name>spring-boot-websocket-demo</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.9.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
    
             <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-websocket</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
    

    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<Session> 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<Session> 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> T getBean(Class<T> clazz) {
            return getApplicationContext().getBean(clazz);
        }
    
        // 通过name,以及Clazz返回指定的Bean
        public static <T> T getBean(String name, Class<T> 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目录下

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>My WebSocket</title>
    </head>
    <body>
    Welcome<br/>
    <input id="text" type="text"/>
    <button onclick="send()">发送</button>
    <button onclick="closeWebSocket()">关闭连接</button>
    <div id="message">
    </div>
    </body>
    
    <script type="text/javascript">
        var websocket = null;
        var host = "";
        if (window.location.protocol == 'http:') {
            host = 'ws://localhost:8585/websocket';
        } else {
            host = 'wss://localhost:8585/websocket';
        }
        //判断当前浏览器是否支持WebSocket
    
        if ('WebSocket' in window) {
            websocket = new WebSocket(host);
        } else if ('MozWebSocket' in window) {
            websocket = new MozWebSocket(host);
        } else {
            alert("该浏览器不支持WebSocket!");
    //        return;
        }
    
        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("连接出错");
        };
    
        //连接成功建立的回调方法
        websocket.onopen = function (event) {
            console.log("连接成功");
            setMessageInnerHTML("已连接服务器!");
        }
    
        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            console.log(event.data);
            setMessageInnerHTML(event.data);
        }
    
        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("连接关闭");
        }
    
        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();
        }
    
        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }
    
        //关闭连接
        function closeWebSocket() {
            websocket.close();
        }
    
        //发送消息
        function send() {
            var message = document.getElementById('text').value;
            websocket.send(message);
        }
    </script>
    </html>
    

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

      本文链接:https://www.haomeiwen.com/subject/erhdpftx.html