1 | /* |
2 | * @(#) $Id: TennisPlayer.java 332218 2005-11-10 03:52:42Z 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 The Apache Directory Project (dev@directory.apache.org) |
16 | * @version $Rev: 332218 $, $Date: 2005-11-10 12:52:42 +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 | } |