java – Tracking connections to ServerSocket. Netty

Question:

I am writing a messenger using the Netty network library. The question is as follows, when the server (ServerSocket) receives a request from the client, it sends a response back, this is all hidden in the library classes and I have implemented it like this:

 */
public class Server {
    EventLoopGroup group = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();

    public void run() throws InterruptedException {
    b.group(group)
.channel(NioServerSocketChannel.class)
.childHandler(new SmartHouseServerInitializer());

    ChannelFuture future= b.bind(9989).sync();
    future.channel().closeFuture().sync();
    group.shutdownGracefully();
}
}
public class SmartHouseServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline p = socketChannel.pipeline();
       // p.addLast(new StringDecoder());
        //p.addLast(new StringEncoder());
        p.addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
        p.addLast(new ObjectEncoder());
        p.addLast( new SmartHouseServerHandler());
    }
}
  public class SmartHouseClientHandler extends SimpleChannelInboundHandler<Object> {
    @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
        String arr=new (String)o;
        ctx.write(arr);
    }

That is, here we receive a request from the client and can immediately send a response to the client, but now there is a need not to respond to the client's request, but to the server itself to initiate sending to the client using the already known channel with it. get a list of them in the future and operate with them, sending requests from the server.

Answer:

In SmartHouseClientHandler you need to override the connection / disconnection methods:

@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    super.channelRegistered(ctx);
    // сохраняем подключение
}

@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    super. channelUnregistered(ctx);
    // удаляем подключение
}

In channelRegistered you can save the connection somewhere in your list. Delete in channelUnregistered . Now you can initiate sending a message from the server to the client through this channel.

Scroll to Top