io.flood.rpc.network.AcceptorImpl.java Source code

Java tutorial

Introduction

Here is the source code for io.flood.rpc.network.AcceptorImpl.java

Source

/*
 * Copyright 2015 The RPC Project
 *
 * The RPC 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 io.flood.rpc.network;

import com.google.common.base.Strings;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static io.flood.common.utils.LogHelper.format;

public class AcceptorImpl extends AbstractSocketWapper implements Acceptor {

    private static final Logger LOG = LoggerFactory.getLogger(AcceptorImpl.class);
    private final MessageDispatcher dispatcher;
    private ServerBootstrap boot = null;
    private List<Channel> serverChannel = new ArrayList<Channel>();
    private String host;
    private int port;
    private int weigth;
    private int id;

    //private Function

    public AcceptorImpl(MessageDispatcher dispatcher) {
        super(dispatcher);
        this.dispatcher = dispatcher;
    }

    public void bind(String ip, int port, int wegiht) {
        if (Strings.isNullOrEmpty(ip)) {
            ip = "0.0.0.0";
        }
        this.host = ip;
        this.port = port;
        this.weigth = wegiht;
        bind(new InetSocketAddress(ip, port));
    }

    private void bind(final SocketAddress address) {
        id = SocketIdGenerator.nextId();
        boot = new ServerBootstrap();
        boot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    protected void initChannel(SocketChannel ch) throws Exception {
                        LinkedHashMap<String, ChannelHandler> handlers = getHandlers();
                        for (Map.Entry<String, ChannelHandler> entry : handlers.entrySet()) {
                            ch.pipeline().addLast(entry.getKey(), entry.getValue());
                        }
                        ch.pipeline().addLast("messageDecoder", new MessageDecoder());
                        ch.pipeline().addLast("messageEncoder", new MessageEncoder());
                        ch.pipeline().addLast("messageHandler", new MessageHandler(AcceptorImpl.this));
                    }
                });

        try {
            final ChannelFuture future = boot.bind(address).sync();

            if (future.isSuccess()) {
                id = SocketIdGenerator.nextId();
                LOG.info(format(id, "socket bind success({})"), address);
                ConnectionManager.put(id, Connection.Type.Server, future.channel());
                onBindCompleted(future);
                future.channel().closeFuture()
                        .addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

                            public void operationComplete(Future<? super Void> completefuture) throws Exception {
                                LOG.info(format(id, "socket closed()"));
                                serverChannel.remove(future.channel());
                            }

                        });
            }

            else {
                LOG.error(format(id, "socket bind failed({})"), address, future.cause());
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public void shutdown() {
        bossGroup.shutdownGracefully();
    }

    public void shutdownAll() {

    }

    public void onBindCompleted(Future<? super Void> completefuture) {

    }

    public int getWeigth() {
        return weigth;
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public int getId() {
        return id;
    }
}