Server Push

    The server-client communication is done by default with a WebSocket connection if the browser and the server support it. If not, Vaadin will fall back to a method supported by the browser. Vaadin Push uses a custom build of the Atmosphere framework for client-server communication.

    The server push support in Vaadin requires the separate Vaadin Push library. It is included in the installation package as vaadin-push.jar.

    With Ivy, you can get it with the following declaration in the ivy.xml:

    XML

    In some servers, you may need to exlude a sl4j dependency as follows:

    XML

    1. rev="&vaadin.version;" conf="default->default">
    2. <exclude org="org.slf4j" name="slf4j-api"/>
    3. </dependency>

    Pay note that the Atmosphere library is a bundle, so if you retrieve the libraries with Ant, for example, you need to retrieve type=”jar,bundle”.

    Retrieving with Maven

    In Maven, you can get the push library with the following dependency in the POM:

    XML

    1. <dependency>
    2. <groupId>com.vaadin</groupId>
    3. <artifactId>vaadin-push</artifactId>
    4. <version>${vaadin.version}</version>
    5. </dependency>

    To enable server push, you need to define the push mode either in the deployment descriptor or with the @Push annotation for the UI.

    You can use server push in two modes: automatic and manual. The automatic mode pushes changes to the browser automatically after access() finishes. With the manual mode, you can do the push explicitly with push(), which allows more flexibility.

    Sever push can use several transports: WebSockets, long polling, or combined WebSockets+XHR. WebSockets is the default transport.

    The @Push annotation

    You can enable server push for a UI with the @Push annotation as follows. It defaults to automatic mode ( PushMode.AUTOMATIC).

    1. @Push
    2. public class PushyUI extends UI {

    To enable manual mode, you need to give the PushMode.MANUAL parameter as follows:

    Java

    1. @Push(PushMode.MANUAL)
    2. public class PushyUI extends UI {

    To use the long polling transport, you need to set the transport parameter as Transport.LONG_POLLING as follows:

    Java

    You can enable the server push and define the push mode also in the servlet configuration with the pushmode parameter for the servlet in the web.xml deployment descriptor. If you use a Servlet 3.0 compatible server, you also want to enable asynchronous processing with the async-supported parameter. Note the use of Servlet 3.0 schema in the deployment descriptor.

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app
    3. id="WebApp_ID" version="3.0"
    4. xmlns="http://java.sun.com/xml/ns/javaee"
    5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    6. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    7. <servlet>
    8. <servlet-name>Pushy UI</servlet-name>
    9. <servlet-class>
    10. com.vaadin.server.VaadinServlet</servlet-class>
    11. <init-param>
    12. <param-name>UI</param-name>
    13. <param-value>com.example.my.PushyUI</param-value>
    14. </init-param>
    15. <!-- Enable server push -->
    16. <init-param>
    17. <param-name>pushmode</param-name>
    18. <param-value>automatic</param-value>
    19. </init-param>
    20. <async-supported>true</async-supported>
    21. </web-app>

    Making changes to a UI object from another thread and pushing them to the browser requires locking the user session when accessing the UI. Otherwise, the UI update done from another thread could conflict with a regular event-driven update and cause either data corruption or deadlocks. Because of this, you may only access an UI using the access() method, which locks the session to prevent conflicts. It takes a Runnable which it executes as its parameter.

    For example:

    Java

    1. ui.access(new Runnable() {
    2. @Override
    3. public void run() {
    4. series.add(new DataSeriesItem(x, y));
    5. }
    6. });

    In Java 8, where a parameterless lambda expression creates a runnable, you could simply write:

    Java

    1. ui.access(() ->

    If the push mode is manual, you need to push the pending UI changes to the browser explicitly with the push() method.

    Java

    1. ui.access(new Runnable() {
    2. @Override
    3. public void run() {
    4. series.add(new DataSeriesItem(x, y));
    5. ui.push();
    6. }
    7. });

    Below is a complete example of a case where we make UI changes from another thread.

    See the .

    When sharing data between UIs or user sessions, you need to consider the message-passing mechanism more carefully, as explained next.

    Broadcasting messages to be pushed to UIs in other user sessions requires having some sort of message-passing mechanism that sends the messages to all UIs that register as recipients. As processing server requests for different UIs is done concurrently in different threads of the application server, locking the threads properly is very important to avoid deadlock situations.

    The Broadcaster

    The standard pattern for sending messages to other users is to use a broadcaster singleton that registers the UIs and broadcasts messages to them safely. To avoid deadlocks, it is recommended that the messages should be sent through a message queue in a separate thread. Using a Java ExecutorService running in a single thread is usually the easiest and safest way.

    Java

    1. public class Broadcaster implements Serializable {
    2. static ExecutorService executorService =
    3. Executors.newSingleThreadExecutor();
    4. public interface BroadcastListener {
    5. void receiveBroadcast(String message);
    6. }
    7. private static LinkedList<BroadcastListener> listeners =
    8. new LinkedList<BroadcastListener>();
    9. public static synchronized void register(
    10. BroadcastListener listener) {
    11. listeners.add(listener);
    12. }
    13. public static synchronized void unregister(
    14. BroadcastListener listener) {
    15. listeners.remove(listener);
    16. }
    17. public static synchronized void broadcast(
    18. final String message) {
    19. for (final BroadcastListener listener: listeners)
    20. executorService.execute(new Runnable() {
    21. @Override
    22. public void run() {
    23. listener.receiveBroadcast(message);
    24. }
    25. });
    26. }

    See the .

    In Java 8, you could use lambda expressions for the listeners instead of the interface, and a parameterless expression to create the runnable:

    Java

    1. for (final Consumer<String> listener: listeners)
    2. executorService.execute(() ->
    3. listener.accept(message));

    See the on-line example.

    The receivers need to implement the receiver interface and register to the broadcaster to receive the broadcasts. A listener should be unregistered when the UI expires. When updating the UI in a receiver, it should be done safely as described earlier, by executing the update through the access() method of the UI.

    Java

    1. @Push
    2. implements Broadcaster.BroadcastListener {
    3. VerticalLayout messages = new VerticalLayout();
    4. @Override
    5. protected void init(VaadinRequest request) {
    6. ... build the UI ...
    7. // Register to receive broadcasts
    8. Broadcaster.register(this);
    9. }
    10. // Must also unregister when the UI expires
    11. @Override
    12. public void detach() {
    13. Broadcaster.unregister(this);
    14. super.detach();
    15. }
    16. @Override
    17. public void receiveBroadcast(final String message) {
    18. // Must lock the session to execute logic safely
    19. access(new Runnable() {
    20. @Override
    21. public void run() {
    22. // Show it somehow
    23. messages.addComponent(new Label(message));
    24. }
    25. });
    26. }
    27. }

    See the .

    Sending Broadcasts

    To send broadcasts with a broadcaster singleton, such as the one described above, you would only need to call the broadcast() method as follows.

    1. final TextField input = new TextField();
    2. sendBar.addComponent(input);
    3. Button send = new Button("Send");
    4. send.addClickListener(new ClickListener() {
    5. @Override
    6. public void buttonClick(ClickEvent event) {
    7. // Broadcast the message
    8. Broadcaster.broadcast(input.getValue());
    9. input.setValue("");

    See the .