初步尝试websocket

首先需要引入坐标

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

然后开启websocket支持

/**
 * 开启WebSocket支持
 * @author guochao
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

然后就可以在对应的事件里为所欲为了,通过map用你存入时的key可以取到会话对象,可以发送消息;


/**
 * @author zhengkai.blog.csdn.net
 */
@ServerEndpoint("/infoCar/{token}")
@Component
public class WebSocketServer {

    static Log log = LogFactory.get(WebSocketServer.class);
    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";

    private final WebSocketService webSocketService = SpringUtil.getBean(WebSocketService.class);
    private final CheckToken checkToken = SpringUtil.getBean(CheckToken.class);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        User user = checkToken.queryUserByToken(token);
        if (StringUtils.isBlank(token) || ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("token无效");
        }
        this.userId = String.valueOf(user.getId());
        this.session = session;
        System.out.println("连接成功,用户:" + userId);
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
            //加入set中
        } else {
            webSocketMap.put(userId, this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }
        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        //连接成功时
        String msgJson = JSONObject.toJSONString(new WebSocketMsgView(true, 20000,
                WsRespTypeEnum.OPEN_SUCCESS.getType(), "open_success"));
        try {
            sendMessage(msgJson);
        } catch (IOException e) {
            log.error("用户:" + userId + ",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        System.out.println("连接关闭");
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:" + userId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (StringUtils.isNotBlank(message)) {
            try {
                //解析发送的报文,封装为ws来参obj
                WebSocketParam webSocketParam = JSON.parseObject(message).toJavaObject(WebSocketParam.class);
                User user = checkToken.queryUserByToken(webSocketParam.getToken());
                //根据类型获取对应的响应信息
                WsRequest wsRequest = webSocketService.wsController(user, webSocketParam);
                //编辑接收人
                String recUser = wsRequest.getRecUser().toString();
                //生成json
                String jsonResult = JSONObject.toJSONString(wsRequest.getWebSocketMsgView());
                //发送json
                if (StringUtils.isNotBlank(recUser) && webSocketMap.containsKey(recUser)) {
                    webSocketMap.get(recUser).sendMessage(jsonResult);
                } else {
                    log.error("请求的userId:" + recUser + "不在该服务器上");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:" + userId + ",报文:" + message);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            log.error("用户" + userId + ",不在线!");
        }
    }

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

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

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

如果使用的是sping,这时你想使用容器内的对象是无法使用的,,,一次会话就是一个对象;不能像spirng那样创建一个bean放入容器使用,

解决办法是使用多例创建,或者使用static修饰,

又或者使用hutool的SpringUtil工具提取bean;

从上下文获取wbs服务,不能直接注入,否则初始化的时候就会注入进来,那时候ioc容器还未初始化,没有bean,等到调用的时候再去拿,而且wbs是多例模式,并不会在一开始就创建bean
也可以自己写

@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }
    public ApplicationContext getApplicationContext(){
        return applicationContext;
    }
    public static Object getBean(String beanName){
        return applicationContext.getBean(beanName);
    }
    public static <T> T getBean(Class<T> clazz){
        return (T)applicationContext.getBean(clazz);
    }
}

前端部分稍后补齐

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值