1 20 package org.apache.mina.example.sumup; 21 22 import org.apache.mina.common.IdleStatus; 23 import org.apache.mina.common.IoHandler; 24 import org.apache.mina.common.IoHandlerAdapter; 25 import org.apache.mina.common.IoSession; 26 import org.apache.mina.example.sumup.message.AddMessage; 27 import org.apache.mina.example.sumup.message.ResultMessage; 28 import org.apache.mina.util.SessionLog; 29 30 36 public class ServerSessionHandler extends IoHandlerAdapter { 37 public void sessionOpened(IoSession session) { 38 session.setIdleTime(IdleStatus.BOTH_IDLE, 60); 40 41 session.setAttachment(new Integer (0)); 43 } 44 45 public void messageReceived(IoSession session, Object message) { 46 AddMessage am = (AddMessage) message; 49 50 int sum = ((Integer ) session.getAttachment()).intValue(); 52 int value = am.getValue(); 53 long expectedSum = (long) sum + value; 54 if (expectedSum > Integer.MAX_VALUE || expectedSum < Integer.MIN_VALUE) { 55 ResultMessage rm = new ResultMessage(); 57 rm.setSequence(am.getSequence()); rm.setOk(false); 59 session.write(rm); 60 } else { 61 sum = (int) expectedSum; 63 session.setAttachment(new Integer (sum)); 64 65 ResultMessage rm = new ResultMessage(); 67 rm.setSequence(am.getSequence()); rm.setOk(true); 69 rm.setValue(sum); 70 session.write(rm); 71 } 72 } 73 74 public void sessionIdle(IoSession session, IdleStatus status) { 75 SessionLog.info(session, "Disconnecting the idle."); 76 session.close(); 78 } 79 80 public void exceptionCaught(IoSession session, Throwable cause) { 81 session.close(); 83 } 84 } | Popular Tags |