本文整理匯總了Java中io.netty.bootstrap.Bootstrap類的典型用法代碼示例。如果您正苦於以下問題:Java Bootstrap類的具體用法?Java Bootstrap怎麽用?Java Bootstrap使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Bootstrap類屬於io.netty.bootstrap包,在下文中一共展示了Bootstrap類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: open
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
@Override
public void open() {
EventLoopGroup eventLoop = new NioEventLoopGroup();
bootstrap = new Bootstrap();
bootstrap.group(eventLoop);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3 * 1000);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
// .addLast("logging",new LoggingHandler(LogLevel.INFO))
.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader()))) // in 1
.addLast("handler", new ClientReadHandler()) // in 2
.addLast("encoder", new ObjectEncoder())// out 3
.addLast("idleStateHandler", new IdleStateHandler(0, 1, 0))
.addLast(new ClientIdleHandler());
}
});
}
示例2: connect
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
@Override
public void connect(final InetSocketAddress socketAddress) {
workerGroup = new NioEventLoopGroup(workerGroupThreads);
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap
.group(workerGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.TCP_NODELAY, true)
.handler(clientChannelInitializer);
} catch (final Exception ex) {
throw new ClientException(ex);
}
channel = bootstrap.connect(socketAddress.getAddress().getHostAddress(), socketAddress.getPort()).syncUninterruptibly().channel();
}
示例3: UDPServerSocket
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
this.logger = logger;
try {
bootstrap = new Bootstrap();
group = new NioEventLoopGroup();
bootstrap
.group(group)
.channel(NioDatagramChannel.class)
.handler(this);
channel = bootstrap.bind(interfaz, port).sync().channel();
} catch (Exception e) {
this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
this.logger.critical("Perhaps a server is already running on that port?");
System.exit(1);
}
}
示例4: start
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
public void start(String ip, int port) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new FileClientInitializer(sslCtx));
Channel ch = b.connect(ip, port).sync().channel();
ConfigurationContext.propMap.putIfAbsent(SOCKET_CHANNEL, ch);
}catch(Exception e){
e.printStackTrace();
}
}
示例5: newPool
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
@Override
protected FastdfsPool newPool(InetSocketAddress addr) {
if (LOG.isDebugEnabled()) {
LOG.debug("channel pool created : {}", addr);
}
Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(loopGroup);
bootstrap.remoteAddress(addr);
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
return new FastdfsPool(
bootstrap,
readTimeout,
idleTimeout,
maxConnPerHost
);
}
示例6: main
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
public static void main(String[] args) throws IOException, InterruptedException {
Bootstrap b = new Bootstrap();
b.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
}
});
b.connect("localhost", 8090).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));
future.channel().flush();
future.channel().close();
}
}
});
}
示例7: BinaryClient
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
private BinaryClient(BinaryClientBuilder builder) throws Exception {
this.clientName = builder.clientName;
this.remoteAddress = Objects.requireNonNull(builder.remoteAddress, "remoteAddress");
this.autoReconnect = builder.autoReconnect;
this.decoder = Objects.requireNonNull(builder.decoder, "decoder");
this.encoder = Objects.requireNonNull(builder.encoder, "encoder");
this.factory = Objects.requireNonNull(builder.factory, "factory");
this.onChannelStateChanged = builder.onChannelStateChanged;
this.onExceptionCaught = builder.onExceptionCaught;
this.onConnectionEffective = builder.onConnectionEffective;
this.dispatchMessage = builder.dispatchMessage;
this.heartIntervalSec = builder.heartIntervalSec;
// 內部消息注冊
factory.registerMsg(new ConnectionValidateServerHandler())
.registerMsg(new ConnectionValidateSuccessServerHandler()).registerMsg(new HeartServerHandler());
decodeUtil = SymmetricEncryptionUtil.getDecodeInstance(remoteAddress.getPass());
bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class);
log.info(clientName + " nio init");
bootstrap.group(group).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.handler(new ChannelInitializerImpl());
}
示例8: connect
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
@Override
public void connect() throws IOException, InterruptedException {
workerGroup = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(
//new LoggingHandler(LogLevel.INFO),
new MsgEncoder(),
new MsgDecoder(),
new NettyClientHandler()
);
}
});
ChannelFuture f = b.connect(address, port).sync();
channel = f.channel();
}
示例9: shoot
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
public void shoot(ShootComplete shootComplete) {
Bootstrap b = new Bootstrap();
SslContext sslContext = null;
if (ssl) {
try {
sslContext = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} catch (SSLException e) {
e.printStackTrace();
}
}
b.group(group)
.channel(NioSocketChannel.class)
.handler(new HttpClientInitializer(sslContext));
// Make the connection attempt.
b.connect(host, port).addListener(
(ChannelFutureListener) channelFuture -> {
sendHttpRequest(channelFuture, shootComplete);
});
}
示例10: run
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
public void run() {
try {
Bootstrap boot = new Bootstrap();
boot.group(group)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<DatagramChannel>() {
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
channel = ch;
ch.pipeline().addLast(new UdpChannelHandlerServer(TF2UdpServer.this));
}
});
boot.bind(port).sync().channel().closeFuture();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
示例11: create
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
public Channel create(String bindAddr, int port) throws InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup(1);
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
public void initChannel(NioDatagramChannel ch)
throws Exception {
ch.pipeline().addLast(new PacketDecoder());
SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager);
nodeManager.setMessageSender(messageHandler);
ch.pipeline().addLast(messageHandler);
}
});
return b.bind(bindAddr, port).sync().channel();
}
示例12: getConnection
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
@Override
public Future<Channel> getConnection(HostAndPort address)
{
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.option(CONNECT_TIMEOUT_MILLIS, saturatedCast(connectTimeout.toMillis()))
.handler(new ThriftClientInitializer(
messageFraming,
messageEncoding,
requestTimeout,
socksProxy,
sslContextSupplier));
Promise<Channel> promise = group.next().newPromise();
bootstrap.connect(new InetSocketAddress(address.getHost(), address.getPort()))
.addListener((ChannelFutureListener) future -> notifyConnect(future, promise));
return promise;
}
catch (Throwable e) {
return group.next().newFailedFuture(new TTransportException(e));
}
}
示例13: connect
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
@Override
public void connect() {
this.workerGroup = NettyUtils.createEventLoopGroup(4);
Class<? extends Channel> channelClazz = NettyUtils.getChannel();
ChannelHandler channelInitializer = new SkyllaChannelInitializer(this.config.getProtocol());
Bootstrap bootstrap = new Bootstrap();
try {
channel = bootstrap
.channel(channelClazz)
.group(this.workerGroup)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_BACKLOG, 50)
.handler(channelInitializer)
.connect(this.config.getServerHost(), this.config.getServerPort())
.sync().channel();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
示例14: getChannel
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
/**
* 獲取channel
* @param ip
* @param port
* @return
* @throws InterruptedException
*/
private Channel getChannel(String ip,String port) throws InterruptedException {
String channelKey=getUniqKey(ip, port);
ArrayBlockingQueue<Channel> aq=putIfAbsent(NETTY_CHANNEL,channelKey, new ArrayBlockingQueue<Channel>(BOOTSTRAP_POOL_SIZE*CHANNEL_POOL_SIZE));
aq=null==aq?NETTY_CHANNEL.get(channelKey):aq;
Channel channel=aq.poll(100, TimeUnit.MILLISECONDS);
//判斷是否已經關閉的channel,如果是,不再放入連接池,重新申請連接
if(null!=channel&&(!channel.isActive()||!channel.isOpen()||!channel.isWritable())){
channel.disconnect();
channel=null;
}
Bootstrap bootstrap=null==channel?getBootstrap(ip, port):null;
if(null!=bootstrap){
ChannelFuture f =bootstrap.connect(ip,Integer.parseInt(port)).sync();
if (f.isSuccess())channel=f.channel();
}
return null!=channel?channel:aq.take();
}
示例15: HTTPBuilder
import io.netty.bootstrap.Bootstrap; //導入依賴的package包/類
/** Constructor that sets up the connection */
public HTTPBuilder(HTTPSession session) {
try {
boot = new Bootstrap();
boot.group(session.workGroup)
.channel(HTTPChannel.class)
.handler(new HTTPInitializer(session.uri.scheme(), this));
// Channel setup
onConnectBell = new Bell<Void>();
setUri(session.uri);
setupWithTest();
// Tap bells queue setup
tapBellQueue = new ConcurrentLinkedQueue<Bell<Void>>();
} catch (HTTPException e) {
System.err.println(e.getMessage());
}
}