jestro
jestro

Reputation: 2593

Netty 4.0 on multiple ports with multiple protocols?

I'm looking for a server example that would combine a http handler on port 80 and a protobuf handler on another port in the same jar. Thanks!

Upvotes: 6

Views: 7703

Answers (2)

Dmitry Spikhalsky
Dmitry Spikhalsky

Reputation: 5840

From my perspective, the creation of different ServerBootstraps is not the right way to approach it, because it leads to the creation of unused entities, handlers, double initialization, possible inconsistency between them, EventLoopGroups sharing or cloning, etc.

A good alternative is just to create multiple channels for all required ports in one Bootstrap server. Taking "Writing a Discard Server" example from Netty 4.x "Getting Started", we can replace

    // Bind and start to accept incoming connections.
    ChannelFuture f = b.bind(port).sync(); // (7)

    // Wait until the server socket is closed.
    // In this example, this does not happen, but you can do that to gracefully
    // shut down your server.
    f.channel().closeFuture().sync()

with

    List<Integer> ports = Arrays.asList(8080, 8081);
    Collection<Channel> channels = new ArrayList<>(ports.size());
    for (int port : ports) {
        Channel serverChannel = bootstrap.bind(port).sync().channel();
        channels.add(serverChannel);
    }
    for (Channel ch : channels) {
        ch.closeFuture().sync();
    }

Upvotes: 13

Norman Maurer
Norman Maurer

Reputation: 23567

I don't know what exactly you are looking for. Its just about creating two different ServerBootstrap instances, configure them and call bind(..) thats it.

Upvotes: 10

Related Questions