Java 类io.netty.bootstrap.ChannelFactory 实例源码

项目:flashback    文件:ProxyServer.java   
/**
 * Start proxy server
 * */
public void start()
    throws InterruptedException {
  ServerBootstrap serverBootstrap = new ServerBootstrap();
  serverBootstrap.group(_acceptorGroup, _upstreamWorkerGroup);
  serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() {
    @Override
    public ServerChannel newChannel() {
      return new NioServerSocketChannel();
    }
  });
  serverBootstrap.childHandler(new ProxyInitializer(this));

  //bind
  ChannelFuture future = serverBootstrap.bind(_host, _port);

  //wait for the future
  future.awaitUninterruptibly();
  if (!future.isSuccess()) {
    future.channel().closeFuture().awaitUninterruptibly();
    throw new ChannelException(String.format("Failed to bind to: %s:%d", _host, _port), future.cause());
  } else {
    _allChannels.add(future.channel());
  }
}
项目:little_mitm    文件:ProxyToServerConnection.java   
@Override
protected Future<?> execute() {
    Bootstrap cb = new Bootstrap().group(proxyServer.getProxyToServerWorkerFor(transportProtocol));

    switch (transportProtocol) {
    case TCP:
        LOG.debug("Connecting to server with TCP");
        cb.channelFactory(new ChannelFactory<Channel>() {
            @Override
            public Channel newChannel() {
                return new NioSocketChannel();
            }
        });
        break;
    case UDT:
        LOG.debug("Connecting to server with UDT");
        cb.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
                .option(ChannelOption.SO_REUSEADDR, true);
        break;
    default:
        throw new UnknownTransportProtocolException(transportProtocol);
    }

    cb.handler(new ChannelInitializer<Channel>() {
        protected void initChannel(Channel ch) throws Exception {
            initChannelPipeline(ch.pipeline(), initialRequest);
        };
    });
    cb.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            proxyServer.getConnectTimeout());

    if (localAddress != null) {
        return cb.connect(remoteAddress, localAddress);
    } else {
        return cb.connect(remoteAddress);
    }
}
项目:LittleProxy    文件:ProxyToServerConnection.java   
@Override
protected Future<?> execute() {
    Bootstrap cb = new Bootstrap().group(proxyServer
            .getProxyToServerWorkerFor(transportProtocol));

    switch (transportProtocol) {
    case TCP:
        LOG.debug("Connecting to server with TCP");
        cb.channelFactory(new ChannelFactory<Channel>() {
            @Override
            public Channel newChannel() {
                return new NioSocketChannel();
            }
        });
        break;
    case UDT:
        LOG.debug("Connecting to server with UDT");
        cb.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
                .option(ChannelOption.SO_REUSEADDR, true);
        break;
    default:
        throw new UnknownTransportProtocolError(transportProtocol);
    }

    cb.handler(new ChannelInitializer<Channel>() {
        protected void initChannel(Channel ch) throws Exception {
            initChannelPipeline(ch.pipeline(), initialRequest);
        };
    });
    cb.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            proxyServer.getConnectTimeout());

    if (localAddress != null) {
        return cb.connect(remoteAddress, localAddress);
    } else {
        return cb.connect(remoteAddress);
    }
}
项目:netty4.0.27Learn    文件:SocketTestPermutation.java   
public List<BootstrapComboFactory<Bootstrap, Bootstrap>> datagram() {
    // Make the list of Bootstrap factories.
    List<BootstrapFactory<Bootstrap>> bfs = Arrays.asList(
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory<Channel>() {
                        @Override
                        public Channel newChannel() {
                            return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                        }

                        @Override
                        public String toString() {
                            return NioDatagramChannel.class.getSimpleName() + ".class";
                        }
                    });
                }
            },
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(oioWorkerGroup).channel(OioDatagramChannel.class);
                }
            }
    );

    // Populare the combinations.
    return combo(bfs, bfs);
}
项目:netty4.0.27Learn    文件:EpollSocketTestPermutation.java   
@Override
public List<TestsuitePermutation.BootstrapComboFactory<Bootstrap, Bootstrap>> datagram() {
    // Make the list of Bootstrap factories.
    List<BootstrapFactory<Bootstrap>> bfs = Arrays.asList(
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory<Channel>() {
                        @Override
                        public Channel newChannel() {
                            return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                        }

                        @Override
                        public String toString() {
                            return NioDatagramChannel.class.getSimpleName() + ".class";
                        }
                    });
                }
            },
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollDatagramChannel.class);
                }
            }
    );
    return combo(bfs, bfs);
}
项目:bigio    文件:MeMemberUDP.java   
public DataServerThread() {
    dataBossGroup = new NioEventLoopGroup(DATA_BOSS_THREADS);
    dataWorkerGroup = new NioEventLoopGroup(DATA_WORKER_THREADS);
    try {
        Bootstrap b = new Bootstrap();
        b.group(dataWorkerGroup)
                .channelFactory(new ChannelFactory<Channel>() {
                    @Override
                    public Channel newChannel() {
                        return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                    }

                    @Override
                    public String toString() {
                        return NioDatagramChannel.class.getSimpleName() + ".class";
                    }
                }).handler(new ChannelInitializer<DatagramChannel>() {
                    @Override
                    public void initChannel(DatagramChannel ch) throws Exception {
                        ch.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
                        ch.pipeline().addLast(new DataMessageHandler());
                        if (LOG.isTraceEnabled()) {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
                        }
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        LOG.error("Cannot initialize data server.", cause);
                    }
                });

        // Bind and start to accept incoming connections.
        f = b.bind(getIp(), getDataPort()).sync();
    } catch (InterruptedException ex) {
        LOG.error("Message data interrupted.", ex);
    }
}
项目:appdeck-android    文件:ProxyToServerConnection.java   
@Override
protected Future<?> execute() {
    Bootstrap cb = new Bootstrap().group(proxyServer
            .getProxyToServerWorkerFor(transportProtocol));

    switch (transportProtocol) {
    case TCP:
        LOG.debug("Connecting to server with TCP");
        cb.channelFactory(new ChannelFactory<Channel>() {
            @Override
            public Channel newChannel() {
                return new NioSocketChannel();
            }
        });
        break;
    /*case UDT:
        LOG.debug("Connecting to server with UDT");
        cb.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
                .option(ChannelOption.SO_REUSEADDR, true);
        break;*/
    default:
        throw new UnknownTransportProtocolError(transportProtocol);
    }

    cb.handler(new ChannelInitializer<Channel>() {
        protected void initChannel(Channel ch) throws Exception {
            initChannelPipeline(ch.pipeline(), initialRequest);
        };
    });
    cb.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 40 * 1000);

    if (localAddress != null) {
        return cb.connect(remoteAddress, localAddress);
    } else {
        return cb.connect(remoteAddress);
    }
}
项目:appdeck-android    文件:ProxyToServerConnection.java   
@Override
protected Future<?> execute() {
    Bootstrap cb = new Bootstrap().group(proxyServer
            .getProxyToServerWorkerFor(transportProtocol));

    switch (transportProtocol) {
    case TCP:
        LOG.debug("Connecting to server with TCP");
        cb.channelFactory(new ChannelFactory<Channel>() {
            @Override
            public Channel newChannel() {
                return new NioSocketChannel();
            }
        });
        break;
    /*case UDT:
        LOG.debug("Connecting to server with UDT");
        cb.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
                .option(ChannelOption.SO_REUSEADDR, true);
        break;*/
    default:
        throw new UnknownTransportProtocolError(transportProtocol);
    }

    cb.handler(new ChannelInitializer<Channel>() {
        protected void initChannel(Channel ch) throws Exception {
            initChannelPipeline(ch.pipeline(), initialRequest);
        };
    });
    cb.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 40 * 1000);

    if (localAddress != null) {
        return cb.connect(remoteAddress, localAddress);
    } else {
        return cb.connect(remoteAddress);
    }
}
项目:dnd    文件:UDPMulticastBeacon.java   
/**
 * Creates a new UDPMulticastBeacon.
 * 
 * @param factory
 *            a ChannelFactory
 * @param group
 *            the EventLoopGroup to use for channels and the timer
 * @param executor
 *            the executor for application code and a timer for regularly sending the beacon
 * @param moduleID
 *            the ModuleID to announce
 * @param interval
 *            the interval at which to send beacons
 * @param unit
 *            the unit for interval
 */
public UDPMulticastBeacon(final ChannelFactory<? extends DatagramChannel> factory, final EventLoopGroup group,
        final ScheduledExecutorService executor, final ModuleID moduleID, final long interval, final TimeUnit unit) {
    beacon =
            new AtomicReference<BeaconMessage>(new BeaconMessage(moduleID,
                    Collections.<InetSocketAddress> emptyList()));

    executor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            sendBeacon();
        }
    }, 0, interval, unit);

    final MessageAdapter messageAdapter = new MessageAdapter();
    messageAdapter.addMessageType(BeaconMessage.class);
    final GsonCodec gsonCodec = new GsonCodec(Message.class);
    gsonCodec.registerTypeAdapter(Message.class, messageAdapter);
    gsonCodec.registerTypeAdapter(InetSocketAddress.class, new InetSocketAddressAdapter());
    gsonCodec.registerTypeAdapter(BeaconMessage.class, new BeaconMessageDeserializer());

    this.channelFactory = new UDPMulticastChannelFactory(factory, group, new ChannelInitializer<DatagramChannel>() {
        private final DatagramPacketWrapper datagramPacketWrapper = new DatagramPacketWrapper();
        private final StringEncoder stringEncoder = new StringEncoder();
        private final StringDecoder stringDecoder = new StringDecoder();
        private final ChannelHandler beaconHandler = new BeaconHandler();

        @Override
        protected void initChannel(final DatagramChannel channel) {
            channel.pipeline().addLast(datagramPacketWrapper).addLast(stringEncoder).addLast(stringDecoder)
                    .addLast(gsonCodec).addLast(beaconHandler);

            // Move TARGET_ADDRESS from channel context to handler context
            channel.pipeline().context(DatagramPacketWrapper.class).attr(DatagramPacketWrapper.TARGET_ADDRESS)
                    .set(channel.attr(DatagramPacketWrapper.TARGET_ADDRESS).getAndRemove());
        }
    });
}
项目:Glydar    文件:Glydar.java   
public static void main(String[] args) {
    Stopwatch watch = new Stopwatch();
    watch.start();

    GlydarBootstrap bootstrap = new GlydarBootstrap(args);
    server = new GServer(bootstrap);
    ParaGlydar.setServer(server);
    serverThread = new Thread(server);

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.childHandler(new ProtocolInitializer())
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 32 * 1024)
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024)
            .group(new NioEventLoopGroup())
            .channelFactory(new ChannelFactory<ServerChannel>() {
                @Override
                public ServerChannel newChannel() {
                    return new NioServerSocketChannel();
                }
            })
            .bind(new InetSocketAddress(server.getConfig().getPort()));

    server.setUpWorlds();

    try {
        server.getPluginLoader().loadPlugins();
    } catch (Exception exc) {
        server.getLogger().warning(exc, "Error while loading plugins");
    }

    server.getLogger().info("Server ready on port {0}", server.getConfig().getPort());
    server.getLogger().info("This server is running {0} version {1}", server.getName(), server.getVersion());

    watch.stop();
    server.getLogger().info("Server started in {0}ms", watch.elapsed(TimeUnit.MILLISECONDS));

    server.getCommandReader().start();
    serverThread.start();
}
项目:Glydar.next    文件:Glydar.java   
public static void main(String[] args) {
    Stopwatch watch = new Stopwatch();
    watch.start();

    GlydarBootstrap bootstrap = new GlydarBootstrap(args);
    server = new GServer(bootstrap);
    ParaGlydar.setServer(server);
    serverThread = new Thread(server);

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.childHandler(new ProtocolInitializer())
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 32 * 1024)
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024)
            .group(new NioEventLoopGroup())
            .channelFactory(new ChannelFactory<ServerChannel>() {
                @Override
                public ServerChannel newChannel() {
                    return new NioServerSocketChannel();
                }
            })
            .bind(new InetSocketAddress(server.getConfig().getPort()));

    server.setUpWorlds();

    try {
        server.getPluginLoader().loadPlugins();
    } catch (Exception exc) {
        server.getLogger().warning(exc, "Error while loading plugins");
    }

    server.getLogger().info("Server ready on port {0}", server.getConfig().getPort());
    server.getLogger().info("This server is running {0} version {1}", server.getName(), server.getVersion());

    watch.stop();
    server.getLogger().info("Server started in {0}ms", watch.elapsed(TimeUnit.MILLISECONDS));

    server.getCommandReader().start();
    serverThread.start();
}
项目:codec-modbus    文件:ModbusClientMaster.java   
public ChannelFactory<Channel> getChannelFactory() {
    return channelFactory;
}
项目:codec-modbus    文件:ModbusClientMaster.java   
public void setChannelFactory(ChannelFactory<Channel> channelFactory) {
    this.channelFactory = channelFactory;
}
项目:netty4study    文件:SocketTestPermutation.java   
static List<Entry<Factory<Bootstrap>, Factory<Bootstrap>>> datagram() {
    List<Entry<Factory<Bootstrap>, Factory<Bootstrap>>> list =
            new ArrayList<Entry<Factory<Bootstrap>, Factory<Bootstrap>>>();

    // Make the list of Bootstrap factories.
    List<Factory<Bootstrap>> bfs =
            new ArrayList<Factory<Bootstrap>>();
    bfs.add(new Factory<Bootstrap>() {
        @Override
        public Bootstrap newInstance() {
            return new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory<Channel>() {
                @Override
                public Channel newChannel() {
                   return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                }

                @Override
                public String toString() {
                    return NioDatagramChannel.class.getSimpleName() + ".class";
                }
            });
        }
    });
    bfs.add(new Factory<Bootstrap>() {
        @Override
        public Bootstrap newInstance() {
            return new Bootstrap().group(oioWorkerGroup).channel(OioDatagramChannel.class);
        }
    });

    // Populate the combinations
    for (Factory<Bootstrap> sbf: bfs) {
        for (Factory<Bootstrap> cbf: bfs) {
            final Factory<Bootstrap> sbf0 = sbf;
            final Factory<Bootstrap> cbf0 = cbf;
            list.add(new Entry<Factory<Bootstrap>, Factory<Bootstrap>>() {
                @Override
                public Factory<Bootstrap> getKey() {
                    return sbf0;
                }

                @Override
                public Factory<Bootstrap> getValue() {
                    return cbf0;
                }

                @Override
                public Factory<Bootstrap> setValue(Factory<Bootstrap> value) {
                    throw new UnsupportedOperationException();
                }
            });
        }
    }

    return list;
}
项目:appdeck-android    文件:DefaultHttpProxyServer.java   
private void doStart() {
    ServerBootstrap serverBootstrap = new ServerBootstrap().group(
            serverGroup.clientToProxyBossPools.get(transportProtocol),
            serverGroup.clientToProxyWorkerPools.get(transportProtocol));

    ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {
        protected void initChannel(Channel ch) throws Exception {
            new ClientToProxyConnection(
                    DefaultHttpProxyServer.this,
                    sslEngineSource,
                    authenticateSslClients,
                    ch.pipeline());
        };
    };
    switch (transportProtocol) {
    case TCP:
        Log.i(TAG, "Proxy listening with TCP transport");
        serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() {
            @Override
            public ServerChannel newChannel() {
                return new NioServerSocketChannel();
            }
        });
        break;
    /*case UDT:
        LOG.info("Proxy listening with UDT transport");
        serverBootstrap.channelFactory(NioUdtProvider.BYTE_ACCEPTOR)
                .option(ChannelOption.SO_BACKLOG, 10)
                .option(ChannelOption.SO_REUSEADDR, true);
        break;*/
    default:
        throw new UnknownTransportProtocolError(transportProtocol);
    }
    serverBootstrap.childHandler(initializer);
    serverBootstrap.bind(address).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future)
                throws Exception {
            registerChannel(future.channel());
        }
    }).awaitUninterruptibly();
}
项目:appdeck-android    文件:DefaultHttpProxyServer.java   
private void doStart() {
    ServerBootstrap serverBootstrap = new ServerBootstrap().group(
            serverGroup.clientToProxyBossPools.get(transportProtocol),
            serverGroup.clientToProxyWorkerPools.get(transportProtocol));

    ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {
        protected void initChannel(Channel ch) throws Exception {
            new ClientToProxyConnection(
                    DefaultHttpProxyServer.this,
                    sslEngineSource,
                    authenticateSslClients,
                    ch.pipeline());
        };
    };
    switch (transportProtocol) {
    case TCP:
        LOG.info("Proxy listening with TCP transport");
        serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() {
            @Override
            public ServerChannel newChannel() {
                return new NioServerSocketChannel();
            }
        });
        break;
    /*case UDT:
        LOG.info("Proxy listening with UDT transport");
        serverBootstrap.channelFactory(NioUdtProvider.BYTE_ACCEPTOR)
                .option(ChannelOption.SO_BACKLOG, 10)
                .option(ChannelOption.SO_REUSEADDR, true);
        break;*/
    default:
        throw new UnknownTransportProtocolError(transportProtocol);
    }
    serverBootstrap.childHandler(initializer);
    serverBootstrap.bind(address).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future)
                throws Exception {
            registerChannel(future.channel());
        }
    }).awaitUninterruptibly();
}
项目:netty-netty-5.0.0.Alpha1    文件:SocketTestPermutation.java   
static List<Entry<Factory<Bootstrap>, Factory<Bootstrap>>> datagram() {
    List<Entry<Factory<Bootstrap>, Factory<Bootstrap>>> list =
            new ArrayList<Entry<Factory<Bootstrap>, Factory<Bootstrap>>>();

    // Make the list of Bootstrap factories.
    List<Factory<Bootstrap>> bfs = new ArrayList<Factory<Bootstrap>>();
    bfs.add(new Factory<Bootstrap>() {
        @Override
        public Bootstrap newInstance() {
            return new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory<Channel>() {
                @Override
                public Channel newChannel(EventLoop eventLoop) {
                   return new NioDatagramChannel(eventLoop, InternetProtocolFamily.IPv4);
                }

                @Override
                public String toString() {
                    return NioDatagramChannel.class.getSimpleName() + ".class";
                }
            });
        }
    });
    bfs.add(new Factory<Bootstrap>() {
        @Override
        public Bootstrap newInstance() {
            return new Bootstrap().group(oioWorkerGroup).channel(OioDatagramChannel.class);
        }
    });

    // Populate the combinations
    for (Factory<Bootstrap> sbf: bfs) {
        for (Factory<Bootstrap> cbf: bfs) {
            final Factory<Bootstrap> sbf0 = sbf;
            final Factory<Bootstrap> cbf0 = cbf;
            list.add(new Entry<Factory<Bootstrap>, Factory<Bootstrap>>() {
                @Override
                public Factory<Bootstrap> getKey() {
                    return sbf0;
                }

                @Override
                public Factory<Bootstrap> getValue() {
                    return cbf0;
                }

                @Override
                public Factory<Bootstrap> setValue(Factory<Bootstrap> value) {
                    throw new UnsupportedOperationException();
                }
            });
        }
    }

    return list;
}
项目:dnd    文件:UDPMulticastChannelFactory.java   
/**
 * Initializes a new UDPMulticastChannelFactory.
 * 
 * @param parentFactory
 *            the parent factory
 * @param eventLoopGroup
 *            the EventLoopGroup to use
 * @param handler
 *            the ChannelHandler for new channels
 */
public UDPMulticastChannelFactory(final ChannelFactory<? extends DatagramChannel> parentFactory,
        final EventLoopGroup eventLoopGroup, final ChannelHandler handler) {
    LOGGER.entry(parentFactory, eventLoopGroup, handler);
    this.parentFactory = parentFactory;
    this.eventLoopGroup = eventLoopGroup;
    this.handler = handler;
    LOGGER.exit();
}
项目:dnd    文件:UDPMulticastBeacon.java   
/**
 * Creates a new UDPMulticastBeacon. Beacons will be sent at intervals defined by the default interval
 * {@link #DEFAULT_INTERVAL}. The time unit is given by {@link #DEFAULT_INTERVAL_UNIT}.
 * 
 * @param factory
 *            a ChannelFactory
 * @param group
 *            the EventLoopGroup to use for channels and the timer
 * @param executor
 *            the executor for application code and a timer for regularly sending the beacon
 * @param moduleID
 *            the ModuleID to announce
 */
public UDPMulticastBeacon(final ChannelFactory<? extends DatagramChannel> factory, final EventLoopGroup group,
        final ScheduledExecutorService executor, final ModuleID moduleID) {
    this(factory, group, executor, moduleID, DEFAULT_INTERVAL, DEFAULT_INTERVAL_UNIT);
}