|
Client Callbacks
Definition
A client callback is a client object that can be invoked asynchronously
by the server code. We need to update subscribers when a new message is published
on the server. For this we have to do the following:
- Declare the client interface that can be invoked by the server. The server code
will be able to obtain a client proxy that implements this interface;
- On the client side register an object handler that implements the client interface
and receive the updated message;
- Invoke the client proxy from the server code to send the updated message to registered clients.
The client interface is:
public interface IUploadCallback
{
// send a short message
public void notify( String message );
// split a long message in packets and send in multiple calls
public void packetNotify( String message, boolean isLast );
}
Callback Declaration
The interface must be declared in the application.properties file:
Application.client_interface=msg_notif
Application.client_interface.msg_notif= \
com.accendia.datasynch.interfaces.IUploadCallback
The declared name of the interface 'msg_notif' is not used by the application code but
is self documenting the application.properties file.
Client Handler Implementation and Registration
The subscriber client implements the client interface as a client handler:
private class UploadCallback implements IUploadCallback
{
private StringBuffer buffer_;
UploadCallback()
{
buffer_ = new StringBuffer();
}
public void notify( String message )
{
print( message );
}
public void packetNotify( String message, boolean isLast )
{
buffer_.append( message );
if( isLast )
{
print( buffer_.toString() );
buffer_ = new StringBuffer();
}
}
private void print( String message )
{
synchronized( Subscriber.this )
{
// setting this flag will prevent printing an older message
// requested by the subscriber after this message received on callback
messageLoaded_ = true;
printMessage( message );
}
}
}
The subscriber registers the client handler at startup:
serverContext_.addHandler( applicationName, new UploadCallback() );
Callback Invocation
The server obtains the client proxy with the call:
(IUploadCallback)ClientContext.getClientProxy()
The client proxy can only be obtained if the above call is made
in a server worker thread not from a thread created by the application.
If called from an application thread the above call would return null.
A server worker thread is a thread created by the server framework and runs application commands, command factories
or session commands. The sample application obtains client proxies in worker threads, stores the proxies and updates
the subscribed clients from an application thread.
|