View Javadoc

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.tennis;
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  
26  /**
27   * A {@link IoHandler} implementation which plays a tennis game.
28   *
29   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
30   */
31  public class TennisPlayer extends IoHandlerAdapter {
32      private static int nextId = 0;
33  
34      /** Player ID **/
35      private final int id = nextId++;
36  
37      @Override
38      public void sessionOpened(IoSession session) {
39          System.out.println("Player-" + id + ": READY");
40      }
41  
42      @Override
43      public void sessionClosed(IoSession session) {
44          System.out.println("Player-" + id + ": QUIT");
45      }
46  
47      @Override
48      public void messageReceived(IoSession session, Object message) {
49          System.out.println("Player-" + id + ": RCVD " + message);
50  
51          TennisBall ball = (TennisBall) message;
52  
53          // Stroke: TTL decreases and PING/PONG state changes.
54          ball = ball.stroke();
55  
56          if (ball.getTTL() > 0) {
57              // If the ball is still alive, pass it back to peer.
58              session.write(ball);
59          } else {
60              // If the ball is dead, this player loses.
61              System.out.println("Player-" + id + ": LOSE");
62              session.close(true);
63          }
64      }
65  
66      @Override
67      public void messageSent(IoSession session, Object message) {
68          System.out.println("Player-" + id + ": SENT " + message);
69      }
70  
71      @Override
72      public void exceptionCaught(IoSession session, Throwable cause) {
73          cause.printStackTrace();
74          session.close(true);
75      }
76  }