1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 *
19 */
20 package org.apache.mina.example.sumup;
21
22 import org.apache.mina.core.service.IoHandler;
23 import org.apache.mina.core.service.IoHandlerAdapter;
24 import org.apache.mina.core.session.IoSession;
25 import org.apache.mina.example.sumup.message.AddMessage;
26 import org.apache.mina.example.sumup.message.ResultMessage;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31 * {@link IoHandler} for SumUp client.
32 *
33 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
34 */
35 public class ClientSessionHandler extends IoHandlerAdapter {
36
37 private final static Logger LOGGER = LoggerFactory.getLogger(ClientSessionHandler.class);
38
39 private final int[] values;
40
41 private boolean finished;
42
43 public ClientSessionHandler(int[] values) {
44 this.values = values;
45 }
46
47 public boolean isFinished() {
48 return finished;
49 }
50
51 @Override
52 public void sessionOpened(IoSession session) {
53 // send summation requests
54 for (int i = 0; i < values.length; i++) {
55 AddMessage m = new AddMessage();
56 m.setSequence(i);
57 m.setValue(values[i]);
58 session.write(m);
59 }
60 }
61
62 @Override
63 public void messageReceived(IoSession session, Object message) {
64 // server only sends ResultMessage. otherwise, we will have to identify
65 // its type using instanceof operator.
66 ResultMessage rm = (ResultMessage) message;
67 if (rm.isOk()) {
68 // server returned OK code.
69 // if received the result message which has the last sequence
70 // number,
71 // it is time to disconnect.
72 if (rm.getSequence() == values.length - 1) {
73 // print the sum and disconnect.
74 LOGGER.info("The sum: " + rm.getValue());
75 session.close(true);
76 finished = true;
77 }
78 } else {
79 // seever returned error code because of overflow, etc.
80 LOGGER.warn("Server error, disconnecting...");
81 session.close(true);
82 finished = true;
83 }
84 }
85
86 @Override
87 public void exceptionCaught(IoSession session, Throwable cause) {
88 session.close(true);
89 }
90 }