【问题标题】:netty 4 How to send message from servernetty 4 如何从服务器发送消息
【发布时间】:2014-07-10 16:14:29
【问题描述】:

如何从服务器本身发送消息,而不是从 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);
}

【问题讨论】:

    标签: java netty


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      保存ChannelHandlerContext,并用它来发送数据给客户端

      【讨论】:

        猜你喜欢
        • 2017-03-08
        • 1970-01-01
        • 1970-01-01
        • 2015-04-15
        • 2015-12-10
        • 1970-01-01
        • 2017-05-23
        • 1970-01-01
        • 2023-03-29
        相关资源
        最近更新 更多