jWebSocket Listeners for Server Application Logic

This section describes how to create your first server-side jWebSocket Listener. Listeners provide an easy way to process incoming messages from the WebSocket clients as well as events like client connected or client disconnected. Incoming messages are filtered by the jWebSocket filter chain and thus provide the same level of security like plug-ins do.

Unlike plug-ins, listeners are embedded and closely associated with your application code. Hence usually listeners are supposed to implement application specific logic rather than general functionality. However, of course, you are free to implement any logic in listeners as it matches your requirements best and also share the classes across multiple applications. Opposed to plug-ins and their API the main benefit of a listener is that you can directly embed it into your code by simply implementing a single interface.

Creating your first listener and providing its functions to your web site is quite a simple process.

  1. Create a server side listener class
  2. Register your listener at the jWebSocket Server
  3. Create the client side code to process answers of the listener.
  4. Use the listener's functions in your web pages

In the Full Sources Package in download area you will find the jWebSocketServer module. It contains an example for a Token Listener and shows how to simply return some information about the server to the client via jWebSocket Listeners (see code snippets below).

Create a Server Side Listener

The first step to implement a jWebSocket Listener is to create a class which implements WebSocketListener or WebSocketTokenListener. Please refer to our Listeners page to learn how plug-ins work in general. The following listing shows you a simple listener with a single getInfo "command".

public class JWebSocketTokenListenerSample implements WebSocketTokenListener {

  private static Logger log = Logging.getLogger(JWebSocketTokenListenerSample.class);

  public void processOpened(WebSocketEvent aEvent) {
    log.info("Client '" + aEvent.getSessionId() + "' connected.");
  }

  public void processPacket(WebSocketEvent aEvent, WebSocketPacket aPacket) {
    // here you can process any non-token low level message, if desired
  }

  public void processToken(WebSocketTokenEvent aEvent, Token aToken) {
    log.info("Client '" + aEvent.getSessionId() + "' sent Token: '" + aToken.toString() + "'.");
    // here you can interpret the token type sent from the client according to your needs.
    String lNS = aToken.getNS();
    String lType = aToken.getType();

    // check if token has a type and a matching namespace
    if (lType != null && "my.namespace".equals(lNS)) {
      // create a response token
      Token lResponse = aEvent.createResponse(aToken);
      if ("getInfo".equals(lType)) {
        // if type is "getInfo" return some server information
        lResponse.put("vendor", JWebSocketConstants.VENDOR);
        lResponse.put("version", JWebSocketConstants.VERSION_STR);
        lResponse.put("copyright", JWebSocketConstants.COPYRIGHT);
        lResponse.put("license", JWebSocketConstants.LICENSE);
      } else {
        // if unknown type in this namespace, return corresponding error message
        lResponse.put("code", -1);
        lResponse.put("msg", "Token type '" + lType + "' not supported in namespace '" + lNS + "'.");
      }
      aEvent.sendToken(lResponse);
    }
  }

  public void processClosed(WebSocketEvent aEvent) {
    log.info("Client '" + aEvent.getSessionId() + "' disconnected.");
  }
}

Your first jWebSocket Listener

Registering your Listener at the jWebSocket Server

The following listing demonstrates how to register your new listener athe jWebSocket Server.

// get the token server
TokenServer lServer = (TokenServer)JWebSocketFactory.getServer("ts0");
if( lServer != null ) {
  // and add the sample listener to the server's listener chain
  lServer.addListener(new JWebSocketTokenListenerSample());
}

Instantiating your Listener and registering at the Token Server

That's it, the functions of the new sample listener are now available to your clients.

Use the Listener Capabilities in your Web Pages

You can simply use the sendToken method of the jWebSocket JavaScript library in jWebSocket.js to send any token to the server. If you expect a result you can obtain that in the OnMessage method of the TokenClient or you can pass a OnResponse callback for the result as shown in the following listing.

// example how to exchange data with a server side listener
var lToken = {
  ns: "my.namespace",
  type: "getInfo"
};
jWebSocketClient.sendToken( lToken, {
  OnResponse: function( aToken ) {
    log("Server responded: "
      + "vendor: " + aToken.vendor
      + ", version: " + aToken.version
    );
  }
});

Invoking the jWebSocket listener by your client side JavaScript code

Publications

Learn more about WebSockets in general, get background information and gain deeper insight!

Join jWebSocket

Wether developer, designer or translator – join the jWebSocket team and grow together with our success!

Copyright © 2013 Innotrade GmbH. All rights reserved.