Java WebSocket试验(仅用作个人学习)

添加WebSocket依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.6</version>
    <relativePath/>
</parent>

<dependencies>
	 <dependency>
	     <groupId>org.apache.httpcomponents</groupId>
	     <artifactId>httpclient</artifactId>
	 </dependency>
	
	 <dependency>
	     <groupId>org.apache.httpcomponents</groupId>
	     <artifactId>httpmime</artifactId>
	 </dependency>
	
	 <!-- https://mvnrepository.com/artifact/org.springframework/spring-websocket -->
	 <dependency>
	     <groupId>org.springframework</groupId>
	     <artifactId>spring-websocket</artifactId>
	 </dependency>
 <dependencies>

WebSocket配置

/**
 * WebSocket配置
 *
 * @author Joi
 * @date 2022年05月11日 10:52
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig
//        implements WebSocketConfigurer
{

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

//    @Bean
//    public org.springframework.web.socket.WebSocketHandler customWebSocketHandler() {
//        return new WebSocketHandler();
//    }
//
//    @Override
//    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//        registry.addHandler(customWebSocketHandler(), "/webSocketBySpring/webSocketHandler").addInterceptors(new WebSocketInterceptor()).setAllowedOrigins("*");
//        registry.addHandler(customWebSocketHandler(), "/sockjs/webSocketBySpring/webSocketHandler").addInterceptors(new WebSocketInterceptor()).setAllowedOrigins("*").withSockJS();
//    }

}

WebSocket服务端

/**
 * 消息WebSocket服务端
 *
 * @author Joi
 * @Component 实例化到spring容器,泛指各种组件,不需要归类的时候,需要加上。在websocket必加
 * @ServerEndpoint 将该类定义为一个webSocket的服务端
 * @date 2022年05月31日 10:57
 */
@Slf4j
@Component
@ServerEndpoint(value = "/ws/msg/server")
public class MsgWebSocketServer {

    // 注入业务实现
    @Resource
    private MsgInfoService msgInfoService;

    /**
     * 记录当前在线连接数
     */
    private static final AtomicInteger onlineCount = new AtomicInteger(0);

    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(8);

    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();
    private static Map<String, String> clientParmas = new ConcurrentHashMap<>();


    @PostConstruct
    public void init() {
        //新建定时线程池
        Task task = new Task();
        //用于定时发送
        scheduledExecutorService.scheduleAtFixedRate(task, 1, 10, TimeUnit.SECONDS);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        clients.put(session.getId(), session);
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
        log.info("有一连接关闭:{},当前在线人数为:{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接出错,移除连接,在线数减一
     */
    @OnError
    public void onError(Session session, Throwable error) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
        log.error("WebSocket连接发生错误,连接:{}已断开,当前在线人数为:{}", session.getId(), onlineCount.get());
        error.printStackTrace();
    }


    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息[{}]", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败:{}", e.getMessage());
        }
    }


    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws ParseException {
        log.info("服务端收到客户端[{}]的消息[{}]", session.getId(), message);
        clientParmas.put(session.getId(), message);
        if (!StringUtils.isEmpty(message)) {
            // 前端传输过来是一个base64的字符,转换成一个map
            String deStr = new String(Base64.getDecoder().decode(message));
            Map<Object, Object> map = JSON.parseObject(deStr, Map.class);
            // TODO
            final MsgInfoQO qo = new MsgInfoQO();
//            final PageInfo<MsgInfoVO> messageList = msgInfoService.getMessageListForPerson(qo);
            // TODO 具体业务编写。
            List<String> list = new ArrayList<>();
            //然后推送回前端
            sendMessage(JSON.toJSONString(list), session);

        }
    }


    //定时自动推送数据
    class Task implements Runnable {
        @Override
        public void run() {
            clients.keySet().forEach(key -> {
                Session toSession = clients.get(key);
                if (toSession != null) {
                    String parmas = clientParmas.get(toSession.getId());
                    if (!StringUtils.isEmpty(parmas)) {
                        String deStr = new String(Base64.getDecoder().decode(parmas));
                        Map<Object, Object> map = JSON.parseObject(deStr, Map.class);
                        // TODO 具体业务编写。
                        List<String> list = new ArrayList<>();
                        //然后推送回前端
                        sendMessage(JSON.toJSONString(list), toSession);
                    }
                }
            });

        }
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值