2013-03-15 65 views
0

如何從服務器本身發送消息,而不是從MessageHandlers發送消息?我知道InetSocketAddress,我從MessageHandler存儲它,但我看不到任何方式直接使用套接字。netty 4如何從服務器發送消息

例如:

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

只是存儲在通道上的參考和使用:

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

您可以致電channel.write來自任何線程,也可以從處理程序的外部

0

保存ChannelHandlerContext,並用它將數據發送給客戶端

相關問題