美文网首页
1-Springboot2.0中如何使用websocket

1-Springboot2.0中如何使用websocket

作者: Guoyubo | 来源:发表于2018-09-14 15:10 被阅读0次

参考了(写的很好):https://www.cnblogs.com/bianzy/p/5822426.html
springboot2.0实现websocket非常简单,基本几个注解就可以实现长连接,主动下发消息

前提:

springboot: 2.0.4.RELEASE

1 pom

springboot的高级组件会自动引用基础的组件,直接引入spring-boot-starter-websocket就可以了,不再需要引入spring-boot-starter-web和spring-boot-starter,所以不要重复引入。

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <!--<artifactId>spring-boot-starter-web</artifactId>-->
 </dependency>
2 配置类

核心是@ServerEndpoint这个注解。这个注解是Javaee标准里的注解,tomcat7以上已经对其进行了实现  
首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。

要注意,如果使用springboot内置的spring-boot-starter-tomcat跑,那么这个代码加上,如果是打war包放到服务器的tomcat上跑,就得把这段注掉

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

}
3 MyWebSocket
package com.beacool.pressure_sensor_demo.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    public static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    private static Logger log = LoggerFactory.getLogger("fileInfoLog");


    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("有新连接加入!当前在线人数为" + getOnlineCount());
//        try {
//            sendMessage("有新连接加入!当前在线人数为" + getOnlineCount());
//        } catch (IOException e) {
//            System.out.println("IO异常");
//        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        this.session = session;
        message = "来自客户端的消息:" + message;
        log.info(message);
        try {
            sendMessage( message);
        } catch (IOException e) {
            log.error("onMessage方法异常"+e.toString());
            e.printStackTrace();
        }
        //群发消息
//        sendInfo("群发消息"+message);
    }

    /**
     * 发生错误时调用
     @OnError
     **/
     public void onError(Session session, Throwable error) {
         log.error("onMessage方法异常"+error.toString());
         error.printStackTrace();
     }


    /**
     * 发送消息需注意方法加锁synchronized,避免阻塞报错
     * 注意session.getBasicRemote()与session.getAsyncRemote()的区别
     * @param message
     * @throws IOException
     */
     public synchronized void sendMessage(String message) throws IOException {
//         this.session.getBasicRemote().sendText(message);
        this.session.getAsyncRemote().sendText(message);
     }


     /**
      * 群发自定义消息
      * */
    public static void sendInfo(String message) throws IOException {
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}
4 关于群发

我的业务逻辑是需要在某个方法里群发消息后再返回数据给其他服务器,而群发比较耗时,所以专门写了这个类异步实现群发消息(直接Autowired注入使用就行),同时为了避免偶然群发时出现阻塞报错,线程安全的问题

(java.lang.IllegalStateException: The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid state for called method),

所以在上面的sendMessage方法上加了锁synchronized
出错的具体解释见 https://blog.csdn.net/qq_20641565/article/details/80857408

package com.beacool.pressure_sensor_demo.websocket;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 异步群发websocket,防止方法调用时太耗时
 */
@Component
public class AsyncAllSend {
    /**
     * 群发自定义消息
     * */
    @Async
    public void sendInfo(String message) throws IOException {
        for (MyWebSocket item : MyWebSocket.webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }
}
5 连接

访问ws://IP:8080/websocket就可以连接了
有在线websocket模拟工具可以模拟的,地址 http://www.bejson.com/httputil/websocket/

6 吐槽

我这也是看的别人的,然后自己遇坑再填的,我一直想直接在springboot官网上直接看文档,又不知道怎么找文档,就比如这个websocket怎么用,官网完全不知道在哪啊,大神都是怎么找到的????????不能总是用人家现成的吧,麻烦知道的告诉下。
吐槽下,平时学springboot其他方面,比如log4j配置,感觉官网说的是真的不清楚。。。告诉我,我不是一个人!

相关文章

  • 1-Springboot2.0中如何使用websocket

    参考了(写的很好):https://www.cnblogs.com/bianzy/p/5822426.htmlsp...

  • OC中WebSocket的使用

    在OC中webSocket一般使用SocketRocket 是facebook对webSocket的封装githu...

  • WebSocket - iOS

    开发中要使用WebSocket,做到实时监控消息,需要用的技术是websocket。 Swift-WebSocke...

  • 【Java基础】WebSocket在Spring中的使用

    WebSocket 使用 关于怎么使用WebSocket,以及WebSocket的一些概念,这篇文章[https:...

  • webflux中websocket使用

    实现方式 在spring中使用websocket有多种方式: 在spring mvc中使用,这种不做介绍 在web...

  • Websocket

    使用WebSocket WebSocket 接受一个url参数,然后使用WebSocket对象的构造函数来建立与服...

  • Express Websocket使用

    本文主要介绍express+websocket的使用 WebSocket WebSocket 协议在2008年诞生...

  • websocket

    Websocket 协议 Websocket 遵循 rfc6455 标准。websocket使用HTTP作为它的传...

  • Angular Websocket教程

    Angular Websocket教程 在本教程中,我们将介绍如何实现一个非常简单的基于WebSocket的Ang...

  • 2020-12-07

    vue使用WebSocket接受推送消息 webSocket(){ constthat=this; if(type...

网友评论

      本文标题:1-Springboot2.0中如何使用websocket

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