简体   繁体   English

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

[英]netty 4 How to send message from server

How can i send message from server itself, not from MessageHandlers? 如何从服务器本身发送消息,而不是从MessageHandlers发送消息? I know InetSocketAddress, i stored it from MessageHandler, but i cannot see any way to use the socket directly. 我知道InetSocketAddress,我从MessageHandler存储它,但我看不到任何直接使用套接字的方法。

For example: 例如:

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

How can i add method like 我该如何添加方法呢

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

Just store a reference to the Channel and use: 只需存储对频道的引用并使用:

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

You can call channel.write from any thread and also from outside of the handlers 您可以从任何线程调用channel.write,也可以从处理程序外部调用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM