I'm trying to display messages from a Vertx event bus on an HTML page using Vertx WebSocket. But from my implementation when I test the endpoint on the browser it displays This site can’t be reached. The eventbus publishes radomPrize and the consumer receives them I have seen that on the logs using other implementations. Below is what I have done.
ConsumerController
@Controller
public class ConsumerController implements Function<RoutingContext, Uni<Void>> {
public static final Logger LOGGER = Logger.getLogger(ConsumerController.class.getName());
private final EventBus eventBus;
public ConsumerController(Router router, EventBus eventBus) {
this.eventBus = eventBus;
router.route("/prizes")
.respond(this);
router.route("/static/*").handler(StaticHandler.create().setCachingEnabled(false));
}
@Override
public Uni<Void> apply(RoutingContext ctx) {
ServerWebSocket webSocket = ctx.request().toWebSocketAndAwait();
if (webSocket != null) {
LOGGER.info("WebSocket connection established");
webSocket.textMessageHandler(message -> {
LOGGER.info("Received WebSocket message: " + message);
});
eventBus.consumer("prizes", message -> {
String prize = (String) message.body();
LOGGER.info("Sending prize to WebSocket: " + prize);
webSocket.writeTextMessage("Received Prize: " + prize)
.onItem().invoke(() -> {
LOGGER.info("Message sent successfully");
})
.onFailure().invoke(throwable -> {
LOGGER.info("Failed to send message: " + throwable.getMessage());
})
.subscribe().with(
ignored -> {},
throwable -> LOGGER.info("Subscription failed: " + throwable.getMessage())
);
});
} else {
LOGGER.info("WebSocket connection is null");
}
return null;
}
}
PrizeBrokerVerticle
@Component
public class PrizeBrokerVerticle extends AbstractVerticle {
public static final Logger LOGGER = Logger.getLogger(PrizeBrokerVerticle.class.getName());
private final EventBus eventBus;
private final List<String> availablePrizes = List.of("Apple", "HP", "Dell");
public PrizeBrokerVerticle(EventBus eventBus) {
this.eventBus = eventBus;
}
public void start() {
vertx.setPeriodic(2000, timerId -> {
String randomPrize = generateRandomPrize();
eventBus.publish("prizes", randomPrize);
// LOGGER.info("Prize published to EventBus");
});
}
private String generateRandomPrize() {
Random random = new Random();
int index = random.nextInt(availablePrizes.size());
return availablePrizes.get(index);
}
}
Index.html