netty 4如何从服务器发送消息 [英] netty 4 How to send message from server

查看:68
本文介绍了netty 4如何从服务器发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从服务器本身而不是从MessageHandlers发送消息?我知道InetSocketAddress,我从MessageHandler中存储了它,但是我看不到任何直接使用套接字的方法.

How can i send message from server itself, not from MessageHandlers? I know InetSocketAddress, i stored it from MessageHandler, but i cannot see any way to use the socket directly.

例如:

public class QuoteOfTheMomentServer {

    private final int port;

    public QuoteOfTheMomentServer(int port) {
        this.port = port;
    }

    Bootstrap b;

    public void run() throws Exception {
        b = new Bootstrap();
        try {
            b.group(new NioEventLoopGroup())
             .channel(NioDatagramChannel.class)
             .option(ChannelOption.SO_BROADCAST, true)
             .handler(new QuoteOfTheMomentServerHandler());

            b.bind(port).sync().channel().closeFuture().await();
        } finally {
            b.shutdown();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new QuoteOfTheMomentServer(port).run();
    }
}

如何添加类似方法

public void sendMessage(ByteBuf msg, InetSocketAddr addr) {
    b.send(msg, addr);
}

推荐答案

只需存储对Channel的引用并使用:

Just store a reference to the Channel and use:

channel.write(new DatagramPacket(
                Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                new InetSocketAddress(ip, port)));

您可以从任何线程以及处理程序外部调用channel.write

You can call channel.write from any thread and also from outside of the handlers

这篇关于netty 4如何从服务器发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆