Netty主动推送数据到客户端

需求场景:

随着物联网的发展,随之出现了各种传感器监测数据的实时发送,需要和netty服务器通讯,netty和传感器之间需要保持长连接(换句话说,netty和gateway之间都会主动给对方发送消息)

碰到的问题:
netty作为服务器端如何主动的向传感器发送消息,我尝试当每个传感器连接到netty(TCP/IP)时使用一个map把该channelSocket的id和该channelSocket绑定在一起。

先定义一个ConcurrentHashMap,用来保存当前的连接。

import io.netty.channel.Channel;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by zhou
 */
public class ChannelMap {
    public static int channelNum=0;
    private static ConcurrentHashMap<String,Channel> channelHashMap=null;//concurrentHashmap以解决多线程冲突

    public static ConcurrentHashMap<String, Channel> getChannelHashMap() {
        return channelHashMap;
    }

    public static Channel getChannelByName(String name){
        if(channelHashMap==null||channelHashMap.isEmpty()){
            return null;
        }
        return channelHashMap.get(name);
    }
    public static void addChannel(String name,Channel channel){
        if(channelHashMap==null){
            channelHashMap=new ConcurrentHashMap<String,Channel>(10);
        }
        channelHashMap.put(name,channel);
        channelNum++;
    }
    public static int removeChannelByName(String name){
        if(channelHashMap.containsKey(name)){
            channelHashMap.remove(name);
            return 0;
        }else{
            return 1;
        }
    }
}

在服务器端EchoServerHandler中的ChannelRead中保存当前的连接

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 获取的业务数据
        ByteBuf in = (ByteBuf) msg;
        String request = in.toString(CharsetUtil.UTF_8);
        System.out.println("Server Accept[" + request
                + "]");
        // 保存当前连接
        ChannelMap.addChannel(uuid,ctx.channel());
    }

我在服务器端尝试每间隔一段时间获取这个ConcurrentHashMap如果里面已经有绑定的channelSocket,就使用write方法向客户端发送消息


    @GetMapping("/configFrame")
    public Result<?> configFrame(@RequestParam(name = "sim") String sim) {
        // 16进制 指令

        String receiveStr = "...";

        ConcurrentHashMap<String, Channel> channelHashMap = ChannelMap.getChannelHashMap();
        Channel channel = channelHashMap.get(sim);

        // 判断是否活跃
        if(channel==null || !channel.isActive()){
            ChannelMap.getChannelHashMap().remove(sim);
            return Result.error("连接已经中断");
        }
        // 指令发送
        ByteBuf bufff = Unpooled.buffer();
        // 根据具体业务传输数据
        bufff.writeBytes(receiveStr);

        channel.writeAndFlush(bufff).addListener((ChannelFutureListener) future -> {
            StringBuilder sb = new StringBuilder();
            if(!StringUtils.isEmpty(sim)){
                sb.append("【").append(sim).append("】");
            }
            if (future.isSuccess()) {
                System.out.println(sb.toString()+"回写成功"+receiveStr);
            } else {
                System.out.println(sb.toString()+"回写失败"+receiveStr);
            }
        });
        return Result.ok();
    }

最好还是再写一个定时任务,监测map中的连接是否中断


import io.netty.channel.Channel;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Iterator;
import java.util.Map;

@Configuration      // 1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class ChannelScheduleTask {

    // 3.定时删除不活跃的连接
    @Scheduled(cron = "0/5 * * * * ?")
    private void configureTasks() {
        if(ChannelMap.getChannelHashMap()!=null && ChannelMap.getChannelHashMap().size()>0){
            Iterator<Map.Entry<String, Channel>> iterator = ChannelMap.getChannelHashMap().entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Channel> next = iterator.next();
                String key = next.getKey();
                Channel channel = next.getValue();
                if(!channel.isActive()){
                    ChannelMap.getChannelHashMap().remove(key);
                }
            }
        }
    }
}

 

  • 2
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要在 Netty 中实现 WebSocket 服务端主动客户端推送消息,可以使用 `ChannelGroup` 来管理连接到服务器的 WebSocket 客户端的 `Channel`,然后通过遍历 `ChannelGroup` 并将消息写入每个 `Channel` 来实现消息的推送。 下面是一个示例代码,演示了如何在 Netty 中实现 WebSocket 服务端主动客户端推送消息: ```java public class WebSocketServerHandler extends SimpleChannelInboundHandler<WebSocketFrame> { private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); @Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { // 处理 WebSocket 请求 if (frame instanceof TextWebSocketFrame) { // 处理文本消息 String text = ((TextWebSocketFrame) frame).text(); System.out.println("Received message: " + text); // 推送消息给所有连接的客户端 channelGroup.writeAndFlush(new TextWebSocketFrame("Server: " + text)); } else { // 其他类型的消息,如二进制消息、Ping/Pong 消息等 // ... } } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // 当有客户端连接时,将其添加到 ChannelGroup 中 Channel channel = ctx.channel(); channelGroup.add(channel); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // 当有客户端断开连接时,将其从 ChannelGroup 中移除 Channel channel = ctx.channel(); channelGroup.remove(channel); } // 主动客户端推送消息的方法 public void pushMessageToClients(String message) { channelGroup.writeAndFlush(new TextWebSocketFrame("Server: " + message)); } } ``` 在上述示例中,我们创建了一个静态的 `ChannelGroup` 对象 `channelGroup`,用于存储连接到服务器的 WebSocket 客户端的 `Channel`。当有客户端连接时,将其添加到 `channelGroup` 中;当客户端断开连接时,将其从 `channelGroup` 中移除。 在处理 WebSocket 请求时,如果收到文本消息,我们可以通过调用 `channelGroup.writeAndFlush()` 方法将消息写入每个客户端的 `Channel` 中,实现消息的推送。 此外,我们还添加了一个名为 `pushMessageToClients()` 的方法,用于在服务端主动向所有客户端推送消息。 你可以在适当的时候调用 `pushMessageToClients()` 方法来推送消息给所有连接的客户端。例如,可以在定时任务或其他事件触发的地方调用该方法来主动客户端推送消息。 希望对你有所帮助!如果还有其他问题,请继续提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值