websocket的使用详解

前几个星期项目用到了webSocket,本来担心说没怎么用过,然而用起来轻松上手。(最近项目忙已经好久没写东西了,哈哈)
话不多说上代码。简单粗暴易懂。。。
以下为我使用的websocket配置。

/**
 * 开启WebSocket支持
 */
@Configuration
public class WebSocketConfig {

    //如果用外置tomcat,要注释掉以下代码,否则启动项目会报错,用springboot内置tomcat就得放开以下代码
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

下面是连接发送消息关闭连接配置的类

/**
 * wensocket服务
 *
 */
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {

    /**
     * 用来记录当前在线连接数
     */
    private static int onlineCount = 0;

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

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

    /**
     * 接收userId
     */
    private String userId;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.userId = userId;
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        log.info("连接建立:有一连接【{}】建立,当前在线人数为{}", userId, getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("连接关闭:有一连接【{}】关闭!当前在线人数为{}", userId, getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("客户端消息:收到来自窗口{}的信息:{}", userId, message);
        try {
            Instruction instruction = JSON.parseObject(message, Instruction.class);
            int code = instruction.getCode();
            if (code == INSTRUCTION_0.getCode()) {
                //回执心跳
                this.sendMessage(message);
            } else {
                String appID = instruction.getAppID();
                //发送指令
                for (WebSocketServer webSocketServer : webSocketSet) {
                    if (webSocketServer.userId.equals(appID)) {
                        webSocketServer.sendMessage(message);
                    }
                }
            }
        } catch (Exception e) {
            log.error("消息处理报错", e);
        }
    }

    /**
     * 发生错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误", error);
    }

    /**
     * 单发消息
     *
     * @param message 消息
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("发送消息错误", e);
        }
    }


    /**
     * 单发或群发消息
     *
     * @param message 消息
     * @param userId  用户id
     */
    public void sendInfo(String message, @PathParam("userId") String userId) {
        log.info("发送自定义消息:推送消息到窗口{},推送内容:{}", userId, message);
        for (WebSocketServer webSocketServer : webSocketSet) {
            try {
                //这里可以设定只推送给这个userId的,为null则全部推送
                if (userId == null) {
                    webSocketServer.sendMessage(message);
                } else if (webSocketServer.userId.equals(userId)) {
                    webSocketServer.sendMessage(message);
                }
            } catch (Exception e) {
                log.error("单发或群发消息错误", e);
                continue;
            }
        }
    }

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

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

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

最后是配置的一个发送websocket消息的通用类

/**
 * 指令
 *
 * @Description: 指令
 * @Author: Rui3g
 * @Date: 2019/12/26 10:30
 */
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Instruction implements Serializable {

    /**
     * 标识
     */
    private String appID;

    /**
     * 指令编码
     */
    private Integer code;

    /**
     * 指令包含的传输数据
     */
    private String data;

    /**
     * Message说明
     */
    private String meaaage;
}

使用:new个WebSocketServer
先用实体类填入需要发送的信息,
我的做法是之后把实体转为json;
然后调用sendInfo发送消息,后面跟指定用户的唯一标识。

以上就是后端webSocket的使用。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锐rui3g

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值