View Javadoc

1   /*
2    * @(#) $Id: TennisPlayer.java 264677 2005-08-30 02:44:35Z trustin $
3    */
4   package org.apache.mina.examples.tennis;
5   
6   import org.apache.mina.protocol.ProtocolCodecFactory;
7   import org.apache.mina.protocol.ProtocolHandler;
8   import org.apache.mina.protocol.ProtocolHandlerAdapter;
9   import org.apache.mina.protocol.ProtocolProvider;
10  import org.apache.mina.protocol.ProtocolSession;
11  
12  /***
13   * A {@link ProtocolHandler} implementation which plays a tennis game.
14   * 
15   * @author Trustin Lee (trustin@apache.org)
16   * @version $Rev: 264677 $, $Date: 2005-08-30 11:44:35 +0900 $
17   */
18  public class TennisPlayer implements ProtocolProvider
19  {
20      private final ProtocolHandler HANDLER = new TennisPlayerHandler();
21      
22      public ProtocolCodecFactory getCodecFactory()
23      {
24          throw new UnsupportedOperationException();
25      }
26  
27      public ProtocolHandler getHandler()
28      {
29          return HANDLER;
30      }
31  
32      private static class TennisPlayerHandler extends ProtocolHandlerAdapter
33      {
34          private static int nextId = 0;
35  
36          /*** Player ID **/
37          private final int id = nextId++;
38  
39          public void sessionOpened( ProtocolSession session )
40          {
41              System.out.println( "Player-" + id + ": READY" );
42          }
43  
44          public void sessionClosed( ProtocolSession session )
45          {
46              System.out.println( "Player-" + id + ": QUIT" );
47          }
48  
49          public void messageReceived( ProtocolSession session, Object message )
50          {
51              System.out.println( "Player-" + id + ": RCVD " + message );
52  
53              TennisBall ball = ( TennisBall ) message;
54  
55              // Stroke: TTL decreases and PING/PONG state changes.
56              ball = ball.stroke();
57  
58              if( ball.getTTL() > 0 )
59              {
60                  // If the ball is still alive, pass it back to peer.
61                  session.write( ball );
62              }
63              else
64              {
65                  // If the ball is dead, this player loses.
66                  System.out.println( "Player-" + id + ": LOSE" );
67                  session.close();
68              }
69          }
70  
71          public void messageSent( ProtocolSession session, Object message )
72          {
73              System.out.println( "Player-" + id + ": SENT " + message );
74          }
75      }
76  }