ca.lambtoncollege.hauntedhouse.server.ServerHandler.java Source code

Java tutorial

Introduction

Here is the source code for ca.lambtoncollege.hauntedhouse.server.ServerHandler.java

Source

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package ca.lambtoncollege.hauntedhouse.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Handles a server-side channel.
 */
public class ServerHandler extends SimpleChannelInboundHandler<String> {

    static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static final HashMap<String, Channel> map = GlobalMap.getInstance();

    //private static Channel waiting=GlobalMap.getWaiting();

    @Override
    public void channelActive(final ChannelHandlerContext ctx) {

        try {
            String str = String.format("%d,Welcome to %s Strategic Master service!",
                    PropertyMgr.CONNECTION_ESTABLISHED, InetAddress.getLocalHost().getHostName());
            ctx.writeAndFlush(str + "\n");
            /*
            ctx.writeAndFlush(
            "Your session is protected by "
            + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
            + " cipher suite.\n");
            */
            channels.add(ctx.channel());
            Channel clientB = getClient(ctx.channel());
            if (clientB == null) {
                //str=String.format("%d,,%s", PropertyMgr.WAITING_FOR_ANOTHER_PLAYER,InetAddress.getLocalHost().getHostName());
                System.out.println("Can't get ClientB , WAITING_FOR_ANOTHER_PLAYER!");
            } else {
                str = String.format("%d,%d,%s", PropertyMgr.JOIN_A_GAME, PropertyMgr.TEAMB,
                        InetAddress.getLocalHost().getHostName());
                clientB.writeAndFlush(str + "\n");
                System.out.println("get ClientB , JOIN_A_GAME!");
                str = String.format("%d,%d,%s", PropertyMgr.JOIN_A_GAME, PropertyMgr.TEAMA,
                        InetAddress.getLocalHost().getHostName());
                ctx.writeAndFlush(str + "\n");
            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(ServerHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        /*
        // Once session is secured, send a greeting and register the channel to the global channel
        // list so the channel received the messages from others.
        ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
        new GenericFutureListener<Future<Channel>>() {
        @Override
        public void operationComplete(Future<Channel> future) throws Exception {
        String str=String.format("%d,Welcome to %s Strategic Master service!", PropertyMgr.CONNECTION_ESTABLISHED,InetAddress.getLocalHost().getHostName());
        ctx.writeAndFlush(str+"\n");
            
        ctx.writeAndFlush(
        "Your session is protected by "
        + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
        + " cipher suite.\n");
            
        channels.add(ctx.channel());
        Channel clientB = getClient(ctx.channel());
        if (clientB == null) {
        //str=String.format("%d,,%s", PropertyMgr.WAITING_FOR_ANOTHER_PLAYER,InetAddress.getLocalHost().getHostName());
        System.out.println("Can't get ClientB , WAITING_FOR_ANOTHER_PLAYER!");
        } else {  
        str=String.format("%d,%d,%s", PropertyMgr.JOIN_A_GAME,PropertyMgr.TEAMB,InetAddress.getLocalHost().getHostName());
        clientB.writeAndFlush(str+"\n");
        System.out.println("get ClientB , JOIN_A_GAME!");
        str=String.format("%d,%d,%s", PropertyMgr.JOIN_A_GAME,PropertyMgr.TEAMA,InetAddress.getLocalHost().getHostName());
        ctx.writeAndFlush(str+"\n");
        }
        }
        });
        */

    }

    public void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        // Send the received message to all channels but the current one.
        //        for (Channel c: channels) {
        //            if (c != ctx.channel()) {
        //                c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
        //            } else {
        //                c.writeAndFlush("[you] " + msg + '\n');
        //            }
        //        }
        String str = "";
        Channel clientA = ctx.channel();
        Channel clientB = getClient(clientA);
        String[] array = PropertyMgr.split(msg);
        if (clientB == null) {
            if (array[0].equals(Integer.toString(PropertyMgr.BYE))) {
                GlobalMap.resetWaiting();
                ctx.close();
            }
        } else {
            if (array[0].equals(Integer.toString(PropertyMgr.DURING_THE_GAME))) {
                str = String.format("%d,%s,%s,%s,%s", PropertyMgr.DURING_THE_GAME, array[1], array[2], array[3],
                        clientA.remoteAddress());
                clientB.writeAndFlush(str + "\n");
            } else if (array[0].equals(Integer.toString(PropertyMgr.BYE))) {
                str = String.format("%d,,%s", PropertyMgr.ANOTHER_PLAYER_LOST_THE_CONNECTION,
                        clientA.remoteAddress());
                map.remove(Integer.toString(clientA.hashCode()));
                map.remove(Integer.toString(clientB.hashCode()));
                clientB.writeAndFlush(str + "\n");
                ctx.close();
            }
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //        System.out.println("Server channelRead0==========="+msg+ctx.channel().toString()+" HASHCODE:"+ctx.channel().hashCode());
        //        String clientA = Integer.toString(ctx.channel().hashCode());
        messageReceived(ctx, msg);
    }

    /**
     *
     * @param clientA
     * @return null or Channel represent the Client you are about to talk with
     */
    public Channel getClient(Channel clientA) {
        Channel clientB = map.get(Integer.toString(clientA.hashCode()));
        if (clientB != null) {
            System.err.println("After map.get: " + Integer.toString(clientB.hashCode()));
        } else {
            System.err.println("Mapping Not Found");
        }
        //        System.out.println(""+Integer.toString(codeA.hashCode()));
        if (clientB == null) {
            if (GlobalMap.isWaiting()) {
                clientB = GlobalMap.takeWaiting(clientA);
                if (clientB != null) {
                    System.err.println("After takeWaiting: " + Integer.toString(clientB.hashCode()));
                    System.out.println("Putting " + Integer.toString(clientB.hashCode()) + " into "
                            + Integer.toString(clientA.hashCode()));
                    map.put(Integer.toString(clientA.hashCode()), clientB);
                    System.out.println("Putting " + Integer.toString(clientA.hashCode()) + " into "
                            + Integer.toString(clientB.hashCode()));
                    map.put(Integer.toString(clientB.hashCode()), clientA);
                }
            } else {
                System.out.println("Waiting with " + Integer.toString(clientA.hashCode()));
                GlobalMap.setWaiting(clientA);
            }
        }
        if (clientB != null) {
            System.out.println("Returning " + Integer.toString(clientB.hashCode()));
        } else {
            System.err.println("Returning Null");
        }
        return clientB;
    }

    //    public String matchClient(String codeA) {
    //        String codeB = null;
    //        if(isWaiting(codeA)) {
    //            codeB = takeWaiting();
    //            map.put(codeA, codeB);
    //            map.put(codeB, codeA);
    //        }else {
    //            setWaiting(codeA);
    //        }
    //        return codeB;
    //    }
    //    public void setWaiting(Channel waiting) {
    //        this.waiting = waiting;
    //    }
    //
    //    public Channel takeWaiting(){
    //        Channel temp =getWaiting();
    //        resetWaiting();
    //        return temp;
    //    }
    //    
    //    public void resetWaiting(){
    //        waiting = null;
    //    }
    //    
    //    public Channel getWaiting() {
    //        return waiting;
    //    }
    //    
    //    public boolean isWaiting(Channel code){
    //        return waiting!=null && waiting.equals(code);
    //    }
    //    public boolean isExist(String key){
    //        return map.get(key)!=null ? true : isWaiting(key);
    //    }
}