001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 * 019 */ 020package org.apache.mina.example.sumup; 021 022import org.apache.mina.core.service.IoHandler; 023import org.apache.mina.core.service.IoHandlerAdapter; 024import org.apache.mina.core.session.IoSession; 025import org.apache.mina.example.sumup.message.AddMessage; 026import org.apache.mina.example.sumup.message.ResultMessage; 027import org.slf4j.Logger; 028import org.slf4j.LoggerFactory; 029 030/** 031 * {@link IoHandler} for SumUp client. 032 * 033 * @author <a href="http://mina.apache.org">Apache MINA Project</a> 034 */ 035public class ClientSessionHandler extends IoHandlerAdapter { 036 037 private final static Logger LOGGER = LoggerFactory.getLogger(ClientSessionHandler.class); 038 039 private final int[] values; 040 041 private boolean finished; 042 043 public ClientSessionHandler(int[] values) { 044 this.values = values; 045 } 046 047 public boolean isFinished() { 048 return finished; 049 } 050 051 @Override 052 public void sessionOpened(IoSession session) { 053 // send summation requests 054 for (int i = 0; i < values.length; i++) { 055 AddMessage m = new AddMessage(); 056 m.setSequence(i); 057 m.setValue(values[i]); 058 session.write(m); 059 } 060 } 061 062 @Override 063 public void messageReceived(IoSession session, Object message) { 064 // server only sends ResultMessage. otherwise, we will have to identify 065 // its type using instanceof operator. 066 ResultMessage rm = (ResultMessage) message; 067 if (rm.isOk()) { 068 // server returned OK code. 069 // if received the result message which has the last sequence 070 // number, 071 // it is time to disconnect. 072 if (rm.getSequence() == values.length - 1) { 073 // print the sum and disconnect. 074 LOGGER.info("The sum: " + rm.getValue()); 075 session.close(true); 076 finished = true; 077 } 078 } else { 079 // seever returned error code because of overflow, etc. 080 LOGGER.warn("Server error, disconnecting..."); 081 session.close(true); 082 finished = true; 083 } 084 } 085 086 @Override 087 public void exceptionCaught(IoSession session, Throwable cause) { 088 session.close(true); 089 } 090}