public void messageReceived( ProtocolSession session, Object message )
{
// client only sends AddMessage. otherwise, we will have to identify
// its type using instanceof operator.
AddMessage am = ( AddMessage ) message;
// add the value to the current sum.
int sum = ( ( Integer ) session.getAttachment() ).intValue();
int value = am.getValue();
long expectedSum = ( long ) sum + value;
if( expectedSum > Integer.MAX_VALUE || expectedSum < Integer.MIN_VALUE )
{
// if the sum overflows or underflows, return error message
ResultMessage rm = new ResultMessage();
rm.setSequence( am.getSequence() ); // copy sequence
rm.setOk( false );
session.write( rm );
}
else
{
// sum up
sum = ( int ) expectedSum;
session.setAttachment( new Integer( sum ) );
// return the result message
ResultMessage rm = new ResultMessage();
rm.setSequence( am.getSequence() ); // copy sequence
rm.setOk( true );
rm.setValue( sum );
session.write( rm );
}
}