org.server.core.netty.tcp.BaseSession.java Source code

Java tutorial

Introduction

Here is the source code for org.server.core.netty.tcp.BaseSession.java

Source

/**
 * Copyright 20151120 Hxms.
 *
 * Licensed 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 org.server.core.netty.tcp;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.function.Consumer;

import org.server.core.netty.NettyCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * Netty 
 * 
 * @author Hxms
 *         
 */
abstract class BaseSession implements AutoCloseable {

    /**
     * ??
     * 
     * @author Hxms
     *         
     */
    class ChannelEventListen extends ChannelInboundHandlerAdapter {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            super.channelActive(ctx);
            channalActive0((NioSocketChannel) ctx.channel());
        }

    }

    /**
     * ??
     * 
     * @author Hxms
     *         
     */
    class ExceptionHandlerAdapter extends ChannelHandlerAdapter {

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            safeCallHandle(h -> h.onException(cause));
        }
    }

    static final Logger log = LoggerFactory.getLogger(BaseSession.class);

    /**
     * Bootstrap
     */
    Bootstrap bootstrap;

    /**
     * 
     */
    NioSocketChannel channel;

    /**
     * ?
     */
    BaseSessionEvent handler;

    /**
     *  tcp 
     */
    public BaseSession() {
        createBootstrap();
    }

    /**
     *  Bootstrap
     */
    void createBootstrap() {
        // create a new bootstrap
        bootstrap = NettyCenter.singleInstance().newBootstrap();
        // config bootstrap
        safeCallHandle(h -> h.configBootstrap(bootstrap));
        // coifig initialize handler
        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {

            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                configNewChannel(ch);
            }
        });
    }

    /**
     * ? nio socket channel
     * 
     * @param channel
     *            ?
     */
    protected void configNewChannel(NioSocketChannel channel) {
        //  pipeline
        ChannelPipeline pipeline = channel.pipeline();
        // ?
        pipeline.addLast(new ExceptionHandlerAdapter());
        // ?
        pipeline.addLast(new ChannelEventListen());
        // ?
        safeCallHandle(h -> h.configNewChannel(channel));
    }

    /**
     * 
     * 
     * @param millis
     *            
     */
    public void setConnectTimeoutMillis(int millis) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, millis);
    }

    /**
     * ??
     * 
     * @return the handler ??
     */
    public BaseSessionEvent getHandler() {
        return handler;
    }

    /**
     * ??
     * 
     * @param handler
     *            the handler to set ?
     */
    public void setHandler(BaseSessionEvent handler) {
        this.handler = handler;
    }

    /**
     * ??
     * 
     * @param channel
     *            ?
     */
    protected void channalActive0(NioSocketChannel channel) {
    }

    /**
     * ??
     */
    protected void closeChannel() {
        if (channel != null)
            channel.close();
        channel = null;
    }

    /**
     *  handler
     * 
     * @param consumer
     *            
     */
    protected void safeCallHandle(Consumer<BaseSessionEvent> consumer) {
        if (handler != null) {
            try {
                consumer.accept(handler);
            } catch (Throwable e) {
                log.error("BaseSession::Callback . ", e);
            }
        }
    }
}