springboot整合websocket & 服务器主动推送数据到前端

版权声明:版权属 ©胖子ღ牛逼,微信:xuewen-weiboweixin https://blog.csdn.net/z_xuewen/article/details/82972231

       一般前端请求服务器接口都是使用主动请求的模式,有ajax等。但分不同使用场景 有不一样的需求, 比如要求实时性比较高的场景使用ajax则不好实现,且实现了开销也大。所以有了websocket这种长链接的形式保持在前端与服务器的通信协议。

现在很多后端框架都使用springboot,那么如何在springboot中整合websocket服务呢?直接上代码,更加清晰明了!

首先 在 pom 中加入 websocket 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

创建 socketConfig.class 配置类

@Configuration
public class SocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {

        return new ServerEndpointExporter();
    }

}

创建 websocket.class 接口服务类

注意需要声明为@Component ,这样springboot才会注入并管理

@Component
@ServerEndpoint(value = "/webSocket")
public class websocket{

    private Session session;
    private static ConcurrentHashMap<String, SocketService> webSocketSet = new ConcurrentHashMap<String, SocketService>(16);

    // 监听连接
    @OnOpen
    public void onOpen(Session session) throws IOException {
        webSocketSet.put(webSocketSet.size() + "", this);
    }

    // 监听断开连接
    @OnClose
    public void onClose() {
        System.out.println("closed");
    }

    // 监听收到客户端消息
    @OnMessage
    public void onMessage(String message) throws IOException {
        System.out.println(message);
        this.session.getBasicRemote().sendText("return your message :" + message);
    }

    @OnError
    public void onError(Throwable error) {
        System.out.println("error");
    }

    // 发送消息
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    // 模拟群发消息,即服务端统一发送消息给所有已连接的客户端
    public static void sendAll(String message) {
        for (String key : webSocketSet.keySet()) {
            try {
                webSocketSet.get(key).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
}

到此 websocket 的服务端基本功能已经全部写好,前端直接连接 localhost:8080/webSocket 即可。

其实还有一个问题,比如碰到要在某个方法里面调用推送功能的话该如何是好呢?这里使用session进行发送数据,那么每个客户端连接成功时,以上的代码中已经把 session 存到 websocketSet 堆栈中,笔者已经封装好一个sendAll 推送方法,当要在别的逻辑中进行推送时可以直接调用 sendAll 即可。controller 进行推送的示例如下:


@RestController
@RequestMapping(value = "base")
public class BaseController {
    @RequestMapping(value = "base")
    public void base() {
       SocketService.sendAll("服务器消息推送");
    }
}

这里 请求 localhost:8080/base/base ,服务器就好对已经连接上的客户端进行消息推送啦。

猜你喜欢

转载自blog.csdn.net/z_xuewen/article/details/82972231