@Override
public void messageReceived(IoSession 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.getAttribute(SUM_KEY)).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.setAttribute(SUM_KEY, 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);
}
}