netty 4如何从服务器发送消息

时间:2013-03-15 13:52:59

标签: java netty

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

例如:

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);
}

2 个答案:

答案 0 :(得分:2)

只需存储对频道的引用并使用:

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

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

答案 1 :(得分:0)

保存ChannelHandlerContext,并使用它将数据发送到客户端

相关问题