how can I send a message from the Server to the Client using Netty? I know you can do it like
for (Channel c : channels1) {
c.writeAndFlush("TEXT \r\n");
}
but it is only usable from inside the ChatServerHandler Class. Is there a method to send Messages to the Client or how can I make a method which I can call like for example
sendMessageToServer("MESSAGE");
void sendMessageToServer(String message) {
final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
for (Channel c : channels) {
c.writeAndFlush("TEXT \r\n");
}
}
? If I get the Channels like in ChatServerHandler using
final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
I get a Channel size of 0.
final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
This constructs a new ChannelGroup
with nothing inside.
You should have a class extends SimpleChannelInboundHandler<?>
.
The channelActive(ChannelHandlerContext chc)
method is called when something is connected. Simply add Channel
instance to your channels
by channels.add(chc.channel());
You may have to make your ChannelGroup
public so it can be acessed everywhere. Good luck.
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.