栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot集成websocket

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot集成websocket

像目前的直播、弹幕、小游戏等方面都用到了websocet进行长链接,相对于http的一次请求一次响应websocket只需要进行一次握手即长久性的建立链接进行消息互通。

为什么一些场景要用websocet呢?

        http的请求每次都会进行校验而请求头占用了资源的绝大部分,参数内容相对较少,而像直播弹幕这种实时性和大数据量的交互在http请求上肯定会使用轮询的方式,而每次的轮询请求都会进行校验浪费资源和网络代宽。

        使用websocket有两种方式:1是使用sockjs,2是使用h5的标准。使用Html5标准自然更方便简单,所以记录的是配合h5的使用方法。

1. 引入pom

  核心是@ServerEndpoint这个注解。这个注解是Javaee标准里的注解,tomcat7以上已经对其进行了实现,如果是用传统方法使用tomcat发布项目,只要在pom文件中引入javaee标准即可使用。

    
      javax
      javaee-api
      7.0
      provided
    

  但使用springboot的内置tomcat时,就不需要引入javaee-api了,spring-boot已经包含了。使用springboot的websocket功能首先引入springboot组件。

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

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

2. 使用@ServerEndpoint创立websocket endpoint

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

​
package com.an.websocket.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();
    }

}

​

下面是具体业务实现

package com.an.websocket.socket;

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 WebSocket {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

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

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

    
    @onOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addonlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getonlineCount());
        try {
            sendMessage(String.valueOf(this.session.getQueryString()));
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

    
    @onClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subonlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getonlineCount());
    }

    
    @onMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);

        //群发消息
        for (WebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    
     public void onError(Session session, Throwable error) {
     System.out.println("发生错误");
     error.printStackTrace();
     }


     public 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 (WebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

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

    public static synchronized void addonlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subonlineCount() {
        WebSocket.onlineCount--;
    }
}

使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。

虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。

3. 前端代码

websocket的请求端口改成自己后台的端口,这里我用的默认的8080

session.getQueryString()

在进行参数传递的时候同样使用get的拼参方式,后台接收是通过session的queryString,具体可以看后台代码。




    
    My WebSocket


Welcome
4. 效果

每发送一条消息后端也会推送到前端的展示页上,同时后台也会进行记录,可以基于此进行扩展,比如做个聊天室

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/731469.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号