0

I am trying to develop a socket server supporting TCP sockets and WebSockets. I created two ServerBootsraps with their channels and handlers. I started them with different ports with (skipping unnecessary code parts because they are working ok)

...
ChannelFuture channelFuture = serverBootstrap.bind(port);
...
...
ChannelFuture channelFutureWebsocket = serverBootstrapWebSocket.bind(webSocketPort);

In the tutorials I've seen, they were all ending with serverBootstrap.bind(port).sync(); But If I end with sync, the server stops and waits for packets and I cannot start the other server (as expected). If I don't end with sync, the server runs ok but I am doubtful if it will cause an error in the future.

If my method, skipping sync(), is wrong, how can I run 2 different servers simultaneously?

berkayk
  • 2,376
  • 3
  • 21
  • 26

1 Answers1

0

The javadoc on the Future.sync says: "Waits for this future until it is done, and rethrows the cause of the failure if this future failed."

So what you want to do is get both futures and wait on them both instead of waiting on the 1st future before you've even had a chance to bind the 2nd server.

A simple way to wait on 2 futures is to use a while loop and check both futures using non-blocking methods

ChannelFuture bindFuture1 = bootstrap1.bind(port);
ChannelFuture bindFuture2 = bootstrap2.bind(port);

while (!bindFuture1.isDone() && !bindFuture2.isDone()) Thread.Sleep(INTERVAL);

//Evaluate both futures to see if there were any errors, wait for the other future to be done or do whatever else you need to based on your requirements.

I suggest you read up on futures to understand what the sync method does and why it's necessary. Also have a look here: Waiting on a list of Future

CamW
  • 3,223
  • 24
  • 34