java – Tracking connections to ServerSocket. Netty


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 {
.childHandler(new SmartHouseServerInitializer());

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

    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> {
        protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
        String arr=new (String)o;

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.


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

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

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