netty 4如何从服务器发送消息
问题描述:
如何从服务器本身发送消息,而不是从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);
}
答
只是存储在通道上的参考和使用:
channel.write(new DatagramPacket(
Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
new InetSocketAddress(ip, port)));
您可以致电channel.write来自任何线程,也可以从处理程序的外部
答
保存ChannelHandlerContext,并用它将数据发送给客户端