• cdi
  • components
  • contexts
  • converters
  • el
  • eventlisteners
  • exceptionhandlers
  • facesviews
  • filters
  • functions
  • managedbeans
  • push
  • resourcehandlers
  • scripts
  • servlets
  • taghandlers
  • utils
  • validators
  • viewhandlers
 - socket

Available since OmniFaces 2.3

The <o:socket> is an UIComponent whith opens an one-way (server to client) web socket based push connection in client side which can be reached from server side via PushContext interface injected in any CDI/container managed artifact via @Push annotation.

Configuration

First enable the web socket endpoint by below boolean context parameter in web.xml:

<context-param>
    <param-name>org.omnifaces.SOCKET_ENDPOINT_ENABLED</param-name>
    <param-value>true</param-value>
</context-param>

It will install the SocketEndpoint. Lazy initialization of the endpoint via component is unfortunately not possible across all containers (yet). See also WS spec issue 211.

Usage (client)

Declare <o:socket> tag in the JSF view with at least a channel name and an onmessage JavaScript listener function. The channel name may not be an EL expression and it may only contain alphanumeric characters, hyphens, underscores and periods.

Here's an example which refers an existing JavaScript listener function (do not include the parentheses!).

<o:socket channel="someChannel" onmessage="socketListener" />
function socketListener(message, channel, event) {
    console.log(message);
}

Here's an example which declares an inline JavaScript listener function.

<o:socket channel="someChannel" onmessage="function(message) { console.log(message); }" />

The onmessage JavaScript listener function will be invoked with three arguments:

  • message: the push message as JSON object.
  • channel: the channel name, useful in case you intend to have a global listener, or want to manually control the close.
  • event: the raw MessageEvent instance, useful in case you intend to inspect it.

In case your server is configured to run WS container on a different TCP port than the HTTP container, then you can use the optional port attribute to explicitly specify the port.

<o:socket port="8000" ... />

When successfully connected, the web socket is by default open as long as the document is open, and it will auto-reconnect at increasing intervals when the connection is closed/aborted as result of e.g. a network error or server restart. It will not auto-reconnect when the very first connection attempt already fails. The web socket will be implicitly closed once the document is unloaded (e.g. navigating away, close of browser window/tab, etc).

Usage (server)

In WAR side, you can inject PushContext via @Push annotation on the given channel name in any CDI/container managed artifact such as @Named, @WebServlet, etc wherever you'd like to send a push message and then invoke PushContext.send(Object) with any Java object representing the push message.

@Inject @Push
private PushContext someChannel;

public void sendMessage(Object message) {
    someChannel.send(message);
}

By default the name of the channel is taken from the name of the variable into which injection takes place. The channel name can be optionally specified via the channel attribute. The example below injects the push context for channel name foo into a variable named bar.

@Inject @Push(channel="foo")
private PushContext bar;

The message object will be encoded as JSON and be delivered as message argument of the onmessage JavaScript listener function associated with the channel name. It can be a plain vanilla String, but it can also be a collection, map and even a javabean. For supported argument types, see also Json.encode(Object).

Although web sockets support two-way communication, the <o:socket> push is designed for one-way communication, from server to client. In case you intend to send some data from client to server, just continue using JSF ajax the usual way, if necessary from JavaScript on with <o:commandScript> or perhaps <p:remoteCommand> or similar. This has among others the advantage of maintaining the JSF view state, the HTTP session and, importantingly, all security constraints on business service methods. Namely, those security constraints are not available during an incoming web socket message per se. See also a.o. WS spec issue 238.

Scopes and users

By default the web socket is application scoped, i.e. any view/session throughout the web application having the same web socket channel open will receive the same push message. The push message can be sent by all users and the application itself. This is useful for application-wide feedback triggered by site itself such as real time updates of a certain page (e.g. site-wide statistics, top100 lists, stock updates, etc).

The optional scope attribute can be set to session to restrict the push messages to all views in the current user session only. The push message can only be sent by the user itself and not by the application. This is useful for session-wide feedback triggered by user itself (e.g. as result of asynchronous tasks triggered by user specific action).

<o:socket channel="someChannel" scope="session" ... />

The scope attribute can also be set to view to restrict the push messages to the current view only. The push message will not show up in other views in the same session even if it's the same URL. The push message can only be sent by the user itself and not by the application. This is useful for view-wide feedback triggered by user itself (e.g. progress bar tied to a user specific action on current view).

<o:socket channel="someChannel" scope="view" ... />

The scope attribute may not be an EL expression and allowed values are application, session and view, case insensitive.

Additionally, the optional user attribute can be set to the unique identifier of the logged-in user, usually the login name or the user ID. This way the push message can be targeted to a specific user and can also be sent by other users and the application itself. The value of the user attribute must at least implement Serializable and have a low memory footprint, so putting entire user entity is not recommended.

E.g. when you're using container managed authentication or a related framework/library:

<o:socket channel="someChannel" user="#{request.remoteUser}" ... />

Or when you have a custom user entity around in EL as #{someLoggedInUser} which has an id property representing its identifier:

<o:socket channel="someChannel" user="#{someLoggedInUser.id}" ... />

When the user attribute is specified, then the scope defaults to session and cannot be set to application. It can be set to view, but this is kind of unusual and should only be used if the logged-in user represented by user has a shorter lifetime than the HTTP session (e.g. when your application allows changing a logged-in user during same HTTP session without invaliding it — which is in turn poor security practice). If in such case a session scoped socket is reused, undefined behavior may occur when user-targeted push message is sent. It may target previously logged-in user only. This can be solved by setting the scope to view, but better is to fix the logout to invalidate the HTTP session altogether.

In the server side, the push message can be targeted to the user specified in the user attribute via PushContext.send(Object, Serializable). The push message can be sent by all users and the application itself. This is useful for user-specific feedback triggered by other users (e.g. chat, admin messages, etc) or by application's background tasks (e.g. notifications, event listeners, etc).

@Inject @Push
private PushContext someChannel;

public void sendMessage(Object message, User recipientUser) {
    Long recipientUserId = recipientUser.getId();
    someChannel.send(message, recipientUserId);
}

Multiple users can be targeted by passing a Collection holding user identifiers to PushContext.send(Object, Collection).

public void sendMessage(Object message, Group recipientGroup) {
    Collection<Long> recipientUserIds = recipientGroup.getUserIds();
    someChannel.send(message, recipientUserIds);
}

Channel design hints

You can declare multiple push channels on different scopes with or without user target throughout the application. Be however aware that the same channel name can easily be reused across multiple views, even if it's view scoped. It's more efficient if you use as few different channel names as possible and tie the channel name to a specific push socket scope/user combination, not to a specific JSF view. In case you intend to have multiple view scoped channels for different purposes, best is to use only one view scoped channel and have a global JavaScript listener which can distinguish its task based on the delivered message. E.g. by sending the message in server as below:

Map<String, Object> message = new HashMap<>();
message.put("functionName", "someFunction");
message.put("functionData", functionData); // Can be Map or Bean.
someChannel.send(message);

Which is processed in the onmessage JavaScript listener function as below:

function someSocketListener(message) {
    window[message.functionName](message.functionData);
}

function someFunction(data) {
    // ...
}

function otherFunction(data) {
    // ...
}

// ...

Conditionally connecting

You can use the optional connected attribute to control whether to auto-connect the web socket or not.

<o:socket ... connected="#{bean.pushable}" />

It defaults to true and it's under the covers interpreted as a JavaScript instruction whether to open or close the web socket push connection. If the value of the connected or rendered attribute is an EL expression and it becomes false during an ajax request, then any opened push connection will explicitly be closed during oncomplete of that ajax request, even though you did not cover the <o:socket> component in ajax render/update. So make sure the value is tied to at least a view scoped property in case you intend to control it during the view scope.

You can also explicitly set it to false and manually open the push connection in client side by invoking OmniFaces.Push.open(channel), passing the channel name, for example in an onclick listener function of a command button which initiates a long running asynchronous task in server side. This is particularly useful on view scoped sockets which doesn't necessarily need to immediately open on page load.

<h:commandButton ... onclick="OmniFaces.Push.open('foo')">
    <f:ajax ... />
</h:commandButton>
<o:socket channel="foo" scope="view" ... connected="false" />

In case you intend to have an one-time push and don't expect more messages, usually because you only wanted to present the result of an one-time asynchronous action in a manually opened view scoped push socket as in above example, you can optionally explicitly close the push connection from client side by invoking OmniFaces.Push.close(channel), passing the channel name. For example, in the onmessage JavaScript listener function as below:

function someSocketListener(message, channel) {
    // ...
    OmniFaces.Push.close(channel);
}

Noted should be that both ways should not be mixed. Choose either the server side way of an EL expression in connected attribute, or the client side way of explicitly setting connected="false" and manually invoking OmniFaces.Push functions. Mixing them ends up in undefined behavior because the associated JSF view state in the server side can't be notified if a socket is manually opened in client side.

Events (client)

The optional onopen JavaScript listener function can be used to listen on open of a web socket in client side. This will be invoked on the very first connection attempt, regardless of whether it will be successful or not. This will not be invoked when the web socket auto-reconnects a broken connection after the first successful connection.

<o:socket ... onopen="socketOpenListener" />
function socketOpenListener(channel) {
    // ...
}

The onopen JavaScript listener function will be invoked with one argument:

  • channel: the channel name, useful in case you intend to have a global listener.

The optional onclose JavaScript listener function can be used to listen on (ab)normal close of a web socket. This will be invoked when the very first connection attempt fails, or the server has returned close reason code 1000 (normal closure) or 1008 (policy violated), or the maximum reconnect attempts has exceeded. This will not be invoked when the web socket can make an auto-reconnect attempt on a broken connection after the first successful connection.

<o:socket ... onclose="socketCloseListener" />
function socketCloseListener(code, channel, event) {
    if (code == -1) {
        // Web sockets not supported by client.
    } else if (code == 1000) {
        // Normal close (as result of expired session or view).
    } else {
        // Abnormal close reason (as result of an error).
    }
}

The onclose JavaScript listener function will be invoked with three arguments:

  • code: the close reason code as integer. If this is -1, then the web socket is simply not supported by the client. If this is 1000, then it was normally closed. Else if this is not 1000, then there may be an error. See also RFC 6455 section 7.4.1 and CloseReason.CloseCodes API for an elaborate list of all close codes.
  • channel: the channel name, useful in case you intend to have a global listener.
  • event: the raw CloseEvent instance, useful in case you intend to inspect it.

When a session or view scoped socket is automatically closed with close reason code 1000 by the server (and thus not manually by the client via OmniFaces.Push.close(channel)), then it means that the session or view has expired. In case of a session scoped socket you could take the opportunity to let JavaScript show a "Session expired" message and/or immediately redirect to the login page via window.location. In case of a view scoped socket the handling depends on the reason of the view expiration. A view can be expired when the associated session has expired, but it can also be expired as result of (accidental) navigation or rebuild, or when the JSF "views per session" configuration setting is set relatively low and the client has many views (windows/tabs) open in the same session. You might take the opportunity to warn the client and/or let JavaScript reload the page as submitting any form in it would throw ViewExpiredException anyway.

Events (server)

When a web socket has been opened, a new CDI SocketEvent will be fired with @SocketEvent.Opened qualifier. When a web socket has been closed, a new CDI SocketEvent will be fired with @SocketEvent.Closed qualifier. They can only be observed and collected in an application scoped CDI bean as below. Observing in a request/view/session scoped CDI bean is not possible as there's no means of a HTTP request anywhere at that moment.

@ApplicationScoped
public class SocketObserver {

    public void onOpen(@Observes @Opened SocketEvent event) {
        String channel = event.getChannel(); // Returns <o:socket channel>.
        Long userId = event.getUser(); // Returns <o:socket user>, if any.
        // Do your thing with it. E.g. collecting them in a concurrent/synchronized collection.
        // Do note that a single person can open multiple sockets on same channel/user.
    }

    public void onClose(@Observes @Closed SocketEvent event) {
        String channel = event.getChannel(); // Returns <o:socket channel>.
        Long userId = event.getUser(); // Returns <o:socket user>, if any.
        CloseCode code = event.getCloseCode(); // Returns close reason code.
        // Do your thing with it. E.g. removing them from collection.
    }

}

You could take the opportunity to send another push message to an application scoped socket, e.g. "User X has been logged in" (or out) when a session scoped socket is opened (or closed).

Security considerations

If the socket is declared in a page which is only restricted to logged-in users with a specific role, then you may want to add the URL of the push handshake request URL to the set of restricted URLs.

The push handshake request URL is composed of the URI prefix /omnifaces.push/, followed by channel name. So, in case of for example container managed security which has already restricted an example page /user/foo.xhtml to logged-in users with the example role USER on the example URL pattern /user/* in web.xml like below,

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Restrict access to role USER.</web-resource-name>
        <url-pattern>/user/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>USER</role-name>
    </auth-constraint>
</security-constraint>

.. and the page /user/foo.xhtml in turn contains a <o:socket channel="foo">, then you need to add a restriction on push handshake request URL pattern of /omnifaces.push/foo like below.

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Restrict access to role USER.</web-resource-name>
        <url-pattern>/user/*</url-pattern>
        <url-pattern>/omnifaces.push/foo</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>USER</role-name>
    </auth-constraint>
</security-constraint>

As extra security, particularly for those public channels which can't be restricted by security constraints, the <o:socket> will register all so far declared channels in the current HTTP session, and any incoming web socket open request will be checked whether they match the so far registered channels in the current HTTP session. In case the channel is unknown (e.g. randomly guessed or spoofed by endusers or manually reconnected after the session is expired), then the web socket will immediately be closed with close reason code 1008 (CloseReason.CloseCodes.VIOLATED_POLICY). Also, when the HTTP session gets destroyed, all session and view scoped channels which are still open will explicitly be closed from server side with close reason code 1000 (CloseReason.CloseCodes.NORMAL_CLOSURE). Only application scoped sockets remain open and are still reachable from server end even when the session or view associated with the page in client side is expired.

EJB design hints

In case you'd like to trigger a push from EAR/EJB side to an application scoped push socket, then you could make use of CDI events. First create a custom bean class representing the push event something like PushEvent below taking whatever you'd like to pass as push message.

public final class PushEvent {

    private final String message;

    public PushEvent(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

Then use BeanManager.fireEvent(Object, java.lang.annotation.Annotation...) to fire the CDI event.

@Inject
private BeanManager beanManager;

public void onSomeEntityChange(Entity entity) {
    beanManager.fireEvent(new PushEvent(entity.getSomeProperty()));
}

Note that OmniFaces own Beans.fireEvent(Object, java.lang.annotation.Annotation...) utility method is insuitable as it is not allowed to use WAR (front end) frameworks and libraries like JSF and OmniFaces in EAR/EJB (back end) side.

Finally just @Observes it in some request or application scoped CDI managed bean in WAR and delegate to PushContext as below.

@Inject @Push
private PushContext someChannel;

public void onPushEvent(@Observes PushEvent event) {
    someChannel.send(event.getMessage());
}

Note that a request scoped bean wouldn't be the same one as from the originating page for the simple reason that there's no means of a HTTP request anywhere at that moment. For exactly this reason a view and session scoped bean would not work (as they require respectively the JSF view state and HTTP session which can only be identified by a HTTP request). A view and session scoped push socket would also not work, so the push socket really needs to be application scoped. The FacesContext will also be unavailable in the above event listener method.

In case the trigger in EAR/EJB side is an asynchronous service method which is in turn initiated in WAR side, then you could make use of callbacks from WAR side. Let the business service method take a callback instance as argument, e.g. the java.util.function.Consumer functional interface.

@Asynchronous
public void someAsyncServiceMethod(Entity entity, Consumer<Object> callback) {
    // ... (some long process)
    callback.accept(entity.getSomeProperty());
}

And invoke the asynchronous service method in WAR as below.

@Inject
private SomeService someService;

@Inject @Push
private PushContext someChannel;

public void someAction() {
    someService.someAsyncServiceMethod(entity, message -> someChannel.send(message));
}

This would be the only way in case you intend to asynchronously send a message to a view or session scoped push socket, and/or want to pass something from FacesContext or the initial request/view/session scope along as (final) argument.

In case you're not on Java 8 yet, then you can make use of Runnable as callback instance instead of the above Consumer functional interface example.

@Asynchronous
public void someAsyncServiceMethod(Entity entity, Runnable callback) {
    // ... (some long process)
    entity.setSomeProperty(someProperty);
    callback.run();
}

Which is invoked in WAR as below.

public void someAction() {
    someService.someAsyncServiceMethod(entity, new Runnable() {
        public void run() {
            someChannel.send(entity.getSomeProperty());
        }
    });
}

Note that OmniFaces own Callback interfaces are insuitable as it is not allowed to use WAR (front end) frameworks and libraries like JSF and OmniFaces in EAR/EJB (back end) side.

UI update design hints

In case you'd like to perform complex UI updates, then easiest would be to put <f:ajax> inside <o:socket>. The support was added in OmniFaces 2.6. Here's an example:

<h:panelGroup id="foo">
    ... (some complex UI here) ...
</h:panelGroup>

<h:form>
    <o:socket channel="someChannel" scope="view">
        <f:ajax event="someEvent" listener="#{bean.pushed}" render=":foo" />
    </o:socket>
</h:form>

Here, the push message simply represents the ajax event name. You can use any custom event name.

someChannel.send("someEvent");

An alternative is to combine <o:socket> with <o:commandScript>. E.g.

<h:panelGroup id="foo">
    ... (some complex UI here) ...
</h:panelGroup>

<o:socket channel="someChannel" scope="view" onmessage="someCommandScript" />
<h:form>
    <o:commandScript name="someCommandScript" action="#{bean.pushed}" render=":foo" />
</h:form>

If you pass a Map<String,V> or a JavaBean as push message object, then all entries/properties will transparently be available as request parameters in the command script method #{bean.pushed}.

Demo

Global counter

Below is a static counter which has the same value application wide.

89

If you enable the push, then a websocket will be opened. Note that it's by default always auto-connected when included in the page, but for demo purposes we're initially disabling it.

Push is disconnected

If push is connected and you press the "increment!" button, then the static counter will increment in bean and the push will send out the new value to the same channel in all connected clients. To see it yourself, open the same page in multiple tabs/windows/browsers/machines and trigger the push in only one of it. Note that the counter also won't increment from other side if push is still disconnected on current page.

Realtime stats

You can find here another example of push: realtime stats. This example makes use of CDI events with BeanManager#fireEvent() and @Observes. The custom PageView event is fired in getPage() method of App class.

Scopes and users

You can find here a generic test page of push: scopes and users. This example opens three web sockets of which one is an user-targeted session scoped socket. If you open the same page in a new tab/window in current browser, then you can test application/session/view scoped push. If you open the same page in an incognito window or a different browser, then you can test application scoped push and user-targeted push.

Demo source code
<h3>Global counter</h3>
<p>
    Below is a static counter which has the same value application wide.
</p>

<h1><h:panelGroup id="count">#{pushBean.count}</h:panelGroup></h1>

<h:form>
    <p>
        If you enable the push, then a websocket will be opened.
        Note that it's by default always auto-connected when included in the page, but for demo purposes we're initially disabling it.
    </p>
    <p>
        <h:panelGroup id="toggle">
            Push is #{pushBean.connected ? 'connected' : 'disconnected'} 
            <h:commandButton value="#{pushBean.connected ? 'disconnect' : 'connect'} it" action="#{pushBean.toggle}">
                <f:ajax render="toggle increment :count"/>
            </h:commandButton>
        </h:panelGroup>
    </p>
    <p>
        If push is connected and you press the "increment!" button, then the static counter will increment in bean and the push will send out the new value to the same channel in all connected clients.
        To see it yourself, open the same page in multiple tabs/windows/browsers/machines and trigger the push in only one of it.
        Note that the counter also won't increment from other side if push is still disconnected on current page.
    </p>
    <p>
        <h:commandButton id="increment" value="increment!" action="#{pushBean.increment}" disabled="#{not pushBean.connected}">
            <f:ajax />
        </h:commandButton>
    </p>
</h:form>


<!-- NOTE: having inline script in XHTML like below is bad practice. -->
<!-- It's included directly in XHTML just for sake of demo. -->
<!-- In real world code, put it in a JS file :) -->

<script>
    function updateCounter(newvalue) {
        $("#count").text(newvalue);
    }

    function onclosePush(code) {
        if (code == -1) {
            alert("Oops! Your browser doesn't seem to support web sockets. The push functionality won't work.")
        }
        else if (code != 1000) {
            alert("Oops! Push has stopped working with error code " + code + "! Reload the page.")
        }
    }
</script>

<!-- End of bad practice ;) -->


<o:socket port="8000" channel="counter" onmessage="updateCounter" onclose="onclosePush" connected="#{pushBean.connected}" />

<h3>Realtime stats</h3>
<p>
    You can find here another example of push:
    <h:link value="realtime stats" outcome="/push-stats" />.
    This example makes use of CDI events with <code>BeanManager#fireEvent()</code> and <code>@Observes</code>.
    The custom <code>PageView</code> event is fired in <code>getPage()</code> method of
    <a href="https://github.com/omnifaces/showcase/blob/master/src/main/java/org/omnifaces/showcase/App.java"><code>App</code></a>
    class.
</p>

<h3>Scopes and users</h3>
<p>
    You can find here a generic test page of push:
    <h:link value="scopes and users" outcome="/push-test" />.
    This example opens three web sockets of which one is an user-targeted session scoped socket.
    If you open the same page in a new tab/window in current browser, then you can test application/session/view scoped push.
    If you open the same page in an incognito window or a different browser, then you can test application scoped push and user-targeted push.
</p>