WebSocket allows server side push events using OmniFaces o:socket
. Faces
f:websocket
is not currently working
due to an open MyFaces defect: MYFACES-4685
<div class="card">
<h:form id="frmSocket">
<o:socket scope="view" channel="pushChannel" onmessage="function(m){console.log(m);}">
<f:ajax event="quarkusMessage" render="frmSocket:txt_count"/>
</o:socket>
<h1 class="text-center">
<h:outputText id="txt_count" value="#{webSocketView.count}"/>
</h1>
</h:form>
</div>
package org.primefaces.showcase.view.ajax;
import jakarta.annotation.PostConstruct;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.io.Serial;
import java.io.Serializable;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.jbosslog.JBossLog;
import org.omnifaces.cdi.Push;
import org.omnifaces.cdi.PushContext;
@Named
@ViewScoped
@JBossLog
@RegisterForReflection(serialization = true)
public class WebSocketView implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@Inject
@Push
PushContext pushChannel;
@Getter
@Setter
private int count = 0;
@PostConstruct
public void init() {
// Start a thread to increment count and send message 5 times to simulate some server activity
// NOTE: Do not use threads in your real application this is just to simulate backend activity!
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(5000); // Sleep for 5 seconds
count++;
sendMessage();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
});
thread.start();
}
public void sendMessage() {
log.debugf("Sending message: %d", count);
pushChannel.send("quarkusMessage");
}
}