ca.lambtoncollege.netty.chat.SecureChatServerHandler.java Source code

Java tutorial

Introduction

Here is the source code for ca.lambtoncollege.netty.chat.SecureChatServerHandler.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.netty.chat;

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.handler.ssl.SslHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.net.InetAddress;
import java.util.HashMap;

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

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

    @Override
    public void channelActive(final ChannelHandlerContext ctx) {
        // 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 {
                        ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName()
                                + " secure chat service!\n");
                        ctx.writeAndFlush("Your session is protected by "
                                + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
                                + " cipher suite.\n");
                        channels.add(ctx.channel());
                    }
                });
    }

    public void messageReceived(ChannelHandlerContext ctx, String msg, Channel channel) 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');
        //            }
        //        }

        System.out.println(channel);
        if (channel != null) {
            channel.writeAndFlush("[" + channel.remoteAddress() + "] " + msg + '\n');
        }
        //        ctx.channel().writeAndFlush("[you] " + msg + '\n');

        // Close the connection if the client has sent 'bye'.
        if ("bye".equals(msg.toLowerCase())) {
            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());
        Channel clientB = getClient(ctx.channel());
        if (clientB != null) {
            messageReceived(ctx, msg, clientB);
        } else {
            channelActive(ctx);
        }
        //A:7889046619952953509
    }

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

    //    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);
    //    }
}