protected void run(List<String> messages) throws IOException, InterruptedException { final ByteBuffer buffer = ByteBuffer.allocate(1024); try { // starts the dispatcher listening on port 0 so it selects a random port dispatcher.open(0, 4096); // starts a thread to run the dispatcher which will accept/read connections Thread dispatcherThread = new Thread(dispatcher); dispatcherThread.start(); // create a client connection to the port the dispatcher is listening on final int realPort = dispatcher.getPort(); try (SocketChannel channel = SocketChannel.open()) { channel.connect(new InetSocketAddress("localhost", realPort)); Thread.sleep(100); // send the provided messages for (int i = 0; i < messages.size(); i++) { buffer.clear(); buffer.put(messages.get(i).getBytes(charset)); buffer.flip(); while (buffer.hasRemaining()) { channel.write(buffer); } Thread.sleep(1); } } // wait up to 10 seconds to verify the responses long timeout = 10000; long startTime = System.currentTimeMillis(); while (events.size() < messages.size() && (System.currentTimeMillis() - startTime < timeout)) { Thread.sleep(100); } // should have gotten an event for each message sent Assert.assertEquals(messages.size(), events.size()); } finally { // stop the dispatcher thread and ensure we shut down handler threads dispatcher.close(); } }