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.tennis; 021 022import org.apache.mina.core.service.IoHandler; 023import org.apache.mina.core.service.IoHandlerAdapter; 024import org.apache.mina.core.session.IoSession; 025 026/** 027 * A {@link IoHandler} implementation which plays a tennis game. 028 * 029 * @author <a href="http://mina.apache.org">Apache MINA Project</a> 030 */ 031public class TennisPlayer extends IoHandlerAdapter { 032 private static int nextId = 0; 033 034 /** Player ID **/ 035 private final int id = nextId++; 036 037 @Override 038 public void sessionOpened(IoSession session) { 039 System.out.println("Player-" + id + ": READY"); 040 } 041 042 @Override 043 public void sessionClosed(IoSession session) { 044 System.out.println("Player-" + id + ": QUIT"); 045 } 046 047 @Override 048 public void messageReceived(IoSession session, Object message) { 049 System.out.println("Player-" + id + ": RCVD " + message); 050 051 TennisBall ball = (TennisBall) message; 052 053 // Stroke: TTL decreases and PING/PONG state changes. 054 ball = ball.stroke(); 055 056 if (ball.getTTL() > 0) { 057 // If the ball is still alive, pass it back to peer. 058 session.write(ball); 059 } else { 060 // If the ball is dead, this player loses. 061 System.out.println("Player-" + id + ": LOSE"); 062 session.closeNow(); 063 } 064 } 065 066 @Override 067 public void messageSent(IoSession session, Object message) { 068 System.out.println("Player-" + id + ": SENT " + message); 069 } 070 071 @Override 072 public void exceptionCaught(IoSession session, Throwable cause) { 073 cause.printStackTrace(); 074 session.closeNow(); 075 } 076}