How can i send message from server itself, not from MessageHandlers? I know InetSocketAddress, i stored it from MessageHandler, but i cannot see any way to use the socket directly.
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
保存ChannelHandlerContext,并使用它将数据发送到客户端
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.