I'm using nio to listen for connections on multiple ports. I need to handle each port differently

22 Views Asked by At

I'm using Java nio to listen to multiple TCP ports concurrently. I need to be able to handle connections on different ports differently since I am expecting different requests/data depending on the port. I know I can query the socket for the port once a connection is made but I wonder if there is a cleaner way.

This is how I am creating the listeners, I am using these bean definitions:

    @Bean
    public Selector selector() throws IOException {
        return Selector.open();
    }

    @Bean
    public ServerSocketChannel serverOne() throws IOException {
        ServerSocketChannel server = ServerSocketChannel.open();
        server.configureBlocking(false);
        server.socket().bind(new InetSocketAddress(thePort));
        server.register(selector, SelectionKey.OP_ACCEPT);

        return server;
    }

    @Bean
    public ServerSocketChannel serverTwo() throws IOException {
        ServerSocketChannel server = ServerSocketChannel.open();
        server.configureBlocking(false);
        server.socket().bind(new InetSocketAddress(thePort));
        server.register(selector, SelectionKey.OP_ACCEPT);

        return server;
    }

And then I use this code to listen for and handle incoming connections

        while (selector.isOpen()) {
            selector.select();

            Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
            while (selectionKeys.hasNext()) {
                SelectionKey selectionKey = selectionKeys.next();

                if (selectionKey.isAcceptable()) {
                    SocketChannel socketChannel = ((ServerSocketChannel) selectionKey.channel()).accept();
                    if (socketChannel != null) {
                        // here is where I need to fire off a connection handler specific to the port
                    }
                }
            }
        }

I understand I can use something like socketChannel.socket().getPort() in a case or something but I'd like to keep all the port specific code in the classes where the servers are created.

Thanks for your time!

I tried looking through the classes to see if I could add some sort of meta data and came up empty. I also tried putting the while (selector.isOpen()) { loop in each server been class but no luck.

0

There are 0 best solutions below