Java Code Examples for io.netty.bootstrap.Bootstrap#remoteAddress()
The following examples show how to use
io.netty.bootstrap.Bootstrap#remoteAddress() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestTCPServerSource.java From datacollector with Apache License 2.0 | 6 votes |
private ChannelFuture startTcpClient( TCPServerSourceConfig configBean, EventLoopGroup workerGroup, byte[] data, boolean randomlySlice ) throws InterruptedException { ChannelFuture channelFuture; Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.remoteAddress(new InetSocketAddress("localhost", Integer.parseInt(configBean.ports.get(0)))); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new TCPServerSourceClientHandler(randomlySlice, data)); } }); // Start the client. channelFuture = bootstrap.connect().sync(); return channelFuture; }
Example 2
Source File: RpcNettyConnector.java From hasting with MIT License | 6 votes |
@Override public void startService() { super.startService(); if(this.channel==null){ eventLoopGroup = new NioEventLoopGroup(3); Bootstrap boot = NettyUtils.buildBootStrap(eventLoopGroup,this); boot.remoteAddress(this.getHost(), this.getPort()); try { ChannelFuture f = boot.connect().sync(); f.await(); this.channel = (AbstractChannel)f.channel(); this.fireStartNetListeners(); } catch (InterruptedException e) { logger.info("interrupted start to exist"); this.stopService(); } } }
Example 3
Source File: FastdfsPoolGroup.java From fastdfs-client with Apache License 2.0 | 6 votes |
@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, maxPendingRequests ); }
Example 4
Source File: NettyClient.java From netty-learning-example with Apache License 2.0 | 6 votes |
/** * 重连 */ public void doConnect(Bootstrap bootstrap, EventLoopGroup eventLoopGroup) { try { if (bootstrap != null) { bootstrap.group(eventLoopGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.handler(new NettyClientInitializer()); bootstrap.remoteAddress(host, port); f = bootstrap.connect().addListener((ChannelFuture futureListener) -> { final EventLoop eventLoop = futureListener.channel().eventLoop(); if (!futureListener.isSuccess()) { log.info("与服务端断开连接!在10s之后准备尝试重连!"); eventLoop.schedule(() -> doConnect(new Bootstrap(), eventLoop), 10, TimeUnit.SECONDS); } }); if(initFalg){ log.info("Netty客户端启动成功!"); initFalg=false; } } } catch (Exception e) { log.info("客户端连接失败!"+e.getMessage()); } }
Example 5
Source File: GraphiteClientChannelInitializer.java From gruffalo with Apache License 2.0 | 5 votes |
private Bootstrap configureBootstrap() { Bootstrap bootstrap = new Bootstrap(); bootstrap.remoteAddress(graphiteHost, graphitePort); bootstrap.group(eventLoopGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(this); bootstrap.option(ChannelOption.SO_LINGER, 0); bootstrap.option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT); return bootstrap; }
Example 6
Source File: AbstractSocketTest.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override protected void configure(ServerBootstrap bootstrap, Bootstrap bootstrap2, ByteBufAllocator allocator) { addr = newSocketAddress(); bootstrap.localAddress(addr); bootstrap.option(ChannelOption.ALLOCATOR, allocator); bootstrap.childOption(ChannelOption.ALLOCATOR, allocator); bootstrap2.remoteAddress(addr); bootstrap2.option(ChannelOption.ALLOCATOR, allocator); }
Example 7
Source File: FastdfsPoolGroup.java From azeroth with Apache License 2.0 | 5 votes |
@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); }
Example 8
Source File: PoolTest.java From util4j with Apache License 2.0 | 5 votes |
public static void main(String[] args) { EventLoopGroup group = new NioEventLoopGroup(); final Bootstrap cb = new Bootstrap(); cb.group(group).channel(NioSocketChannel.class); InetSocketAddress addr1 = new InetSocketAddress("10.0.0.10", 8888); InetSocketAddress addr2 = new InetSocketAddress("10.0.0.11", 8888); //连接池map ChannelPoolMap<InetSocketAddress, SimpleChannelPool> poolMap = new AbstractChannelPoolMap<InetSocketAddress, SimpleChannelPool>() { @Override protected SimpleChannelPool newPool(InetSocketAddress key) { return new SimpleChannelPool(cb.remoteAddress(key), new TestChannelPoolHandler()); } }; final SimpleChannelPool pool1 = poolMap.get(addr1);//取出連接addr1地址的连接池 final SimpleChannelPool pool2 = poolMap.get(addr2);//取出連接addr2地址的连接池 Future<Channel> f1 = pool1.acquire();//获取一个连接 f1.addListener(new FutureListener<Channel>() { @Override public void operationComplete(Future<Channel> f) { if (f.isSuccess()) { Channel ch = f.getNow(); //连接地址1的某个channel //使用连接发送消息 // ch.write(msg) //用完释放 pool1.release(ch); } } }); }
Example 9
Source File: BilibiliDanmakuThread.java From BakaDanmaku with MIT License | 5 votes |
@Override public void doRun() { // 获取真实房间 ID String roomID = getRoomId(BakaDanmakuConfig.livePlatform.bilibiliRoom.liveRoom); // 提示,相关房间信息已经获取 sendChatMessage("§8§l直播房间 ID 已经获取,ID 为 " + roomID); EventLoopGroup group = new NioEventLoopGroup(); io.netty.util.Timer timer = new HashedWheelTimer(); try { Bootstrap clientBootstrap = new Bootstrap(); clientBootstrap.group(group); clientBootstrap.channel(NioSocketChannel.class); clientBootstrap.remoteAddress(LIVE_URL, PORT); clientBootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new BilibiliChannalInboundHandler(roomID)); } }); ChannelFuture channelFuture = clientBootstrap.connect().sync(); timer.newTimeout(timeout -> { channelFuture.channel().writeAndFlush(sendDataPack(Unpooled.buffer(), 2, "")); }, 30000, TimeUnit.MILLISECONDS); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException ioe) { ioe.printStackTrace(); } finally { try { timer.stop(); group.shutdownGracefully().sync(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Example 10
Source File: Client.java From Summer with Apache License 2.0 | 5 votes |
public void connect() { try { log.info("client[{}] connect {}:{}", clientContext.getConfig().getServerName(), clientContext.getConfig().getAddress(), clientContext.getConfig().getPort()); Bootstrap b = new Bootstrap(); b.group(workerGroup).channel(NioSocketChannel.class).handler(new ClientInitializer(clientContext)); b.remoteAddress(clientContext.getConfig().getAddress(), clientContext.getConfig().getPort()); b.connect().addListener(new ConnectionListener()); } catch (Exception e) { log.error(e.getMessage(), e); } }
Example 11
Source File: BmpDispatcherUtil.java From bgpcep with Eclipse Public License 1.0 | 5 votes |
public static Bootstrap createClientBootstrap(final @NonNull BmpSessionFactory sessionFactory, final @NonNull BmpHandlerFactory hf, final @NonNull CreateChannel createChannel, final @NonNull BmpSessionListenerFactory slf, final @NonNull InetSocketAddress remoteAddress, final @Nullable SocketAddress localAddress, final @NonNull EventLoopGroup workerGroup, final int connectTimeout, final @NonNull KeyMapping keys, boolean reuseAddress, boolean tryEpollSocket) { final Bootstrap bootstrap = new Bootstrap(); bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); bootstrap.group(workerGroup); bootstrap.handler(createChannel.create(sessionFactory, hf, slf)); if (localAddress != null) { bootstrap.localAddress(localAddress); } bootstrap.remoteAddress(remoteAddress); if (!tryEpollSocket) { bootstrap.channel(NioSocketChannel.class); } else { if (Epoll.isAvailable()) { bootstrap.channel(EpollSocketChannel.class); } else { bootstrap.channel(NioSocketChannel.class); } if (!keys.isEmpty()) { if (Epoll.isAvailable()) { bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys); } else { throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause()); } } } return bootstrap; }
Example 12
Source File: NettyClient.java From springBoot-study with Apache License 2.0 | 5 votes |
/** * 重连 */ public void doConnect(Bootstrap bootstrap, EventLoopGroup eventLoopGroup) { ChannelFuture f = null; try { if (bootstrap != null) { bootstrap.group(eventLoopGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.handler(nettyClientFilter); bootstrap.remoteAddress(host, port); f = bootstrap.connect().addListener((ChannelFuture futureListener) -> { final EventLoop eventLoop = futureListener.channel().eventLoop(); if (!futureListener.isSuccess()) { System.out.println("与服务端断开连接!在10s之后准备尝试重连!"); eventLoop.schedule(() -> doConnect(new Bootstrap(), eventLoop), 10, TimeUnit.SECONDS); } }); if(initFalg){ System.out.println("Netty客户端启动成功!"); initFalg=false; } // 阻塞 f.channel().closeFuture().sync(); } } catch (Exception e) { System.out.println("客户端连接失败!"+e.getMessage()); } }
Example 13
Source File: FixedChannelPoolTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
/** * Tests that the acquiredChannelCount is not added up several times for the same channel acquire request. * @throws Exception */ @Test public void testAcquireNewConnectionWhen() throws Exception { LocalAddress addr = new LocalAddress(LOCAL_ADDR_ID); Bootstrap cb = new Bootstrap(); cb.remoteAddress(addr); cb.group(group) .channel(LocalChannel.class); ServerBootstrap sb = new ServerBootstrap(); sb.group(group) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<LocalChannel>() { @Override public void initChannel(LocalChannel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter()); } }); // Start server Channel sc = sb.bind(addr).syncUninterruptibly().channel(); ChannelPoolHandler handler = new TestChannelPoolHandler(); ChannelPool pool = new FixedChannelPool(cb, handler, 1); Channel channel1 = pool.acquire().syncUninterruptibly().getNow(); channel1.close().syncUninterruptibly(); pool.release(channel1); Channel channel2 = pool.acquire().syncUninterruptibly().getNow(); assertNotSame(channel1, channel2); sc.close().syncUninterruptibly(); channel2.close().syncUninterruptibly(); }
Example 14
Source File: SimpleChannelPoolTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
/** * Tests that if channel was unhealthy it is was offered back to the pool because * it was requested not to validate channel health on release. * * @throws Exception */ @Test public void testUnhealthyChannelIsOfferedWhenNoHealthCheckRequested() throws Exception { EventLoopGroup group = new LocalEventLoopGroup(); LocalAddress addr = new LocalAddress(LOCAL_ADDR_ID); Bootstrap cb = new Bootstrap(); cb.remoteAddress(addr); cb.group(group) .channel(LocalChannel.class); ServerBootstrap sb = new ServerBootstrap(); sb.group(group) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<LocalChannel>() { @Override public void initChannel(LocalChannel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter()); } }); // Start server Channel sc = sb.bind(addr).syncUninterruptibly().channel(); ChannelPoolHandler handler = new CountingChannelPoolHandler(); ChannelPool pool = new SimpleChannelPool(cb, handler, ChannelHealthChecker.ACTIVE, false); Channel channel1 = pool.acquire().syncUninterruptibly().getNow(); channel1.close().syncUninterruptibly(); Future<Void> releaseFuture = pool.release(channel1, channel1.eventLoop().<Void>newPromise()).syncUninterruptibly(); assertThat(releaseFuture.isSuccess(), CoreMatchers.is(true)); Channel channel2 = pool.acquire().syncUninterruptibly().getNow(); //verifying that in fact the channel2 is different that means is not pulled from the pool assertNotSame(channel1, channel2); sc.close().syncUninterruptibly(); channel2.close().syncUninterruptibly(); group.shutdownGracefully(); }
Example 15
Source File: NettyClient.java From netty_push_server with BSD 2-Clause "Simplified" License | 4 votes |
/** * 连接方法 * * @param host * @param port * @throws Exception */ public void sendMessage(final Message message, final INettyClientHandlerListener listener) throws Exception { if (message == null) { return; } if (isConnected()) { // 如果已经连接了则直接发送消息 不必再创建socket连接 if (ctx != null) { ctx.writeAndFlush(message); } return; } System.setProperty("java.net.preferIPv4Stack", "true"); System.setProperty("java.net.preferIPv6Addresses", "false"); ChannelFuture channelFuture = null; group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.TCP_NODELAY, true); b.remoteAddress(new InetSocketAddress(host, port)); // 有连接到达时会创建一个channel b.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); pipeline.addLast("encode", new ObjectEncoder()); pipeline.addLast("decode", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null))); pipeline.addLast("handler", new NettyClientHandler(nettyClient, message, listener)); } }); channelFuture = b.connect().sync(); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { SocketAddress sa = future.channel().remoteAddress(); if (sa != null) { System.out.println("netty server connected success! host:" + sa); // 連接成功 connectState = CONNECT_SUCCESS; } else { System.out.println("netty server connected failed! host:" + sa); // 連接失敗 connectState = CONNECT_FAILED; // 連接 失敗 啟動重連 future.cause().printStackTrace(); future.channel().close(); } } else { System.out.println("netty server attemp failed! host:" + future.channel().remoteAddress()); // 連接失敗 connectState = CONNECT_FAILED; // 連接 失敗 啟動重連 future.cause().printStackTrace(); future.channel().close(); } } }); } finally { disconnect(channelFuture); } }
Example 16
Source File: AbstractClientSocketTest.java From netty4.0.27Learn with Apache License 2.0 | 4 votes |
@Override protected void configure(Bootstrap bootstrap, ByteBufAllocator allocator) { addr = newSocketAddress(); bootstrap.remoteAddress(addr); bootstrap.option(ChannelOption.ALLOCATOR, allocator); }
Example 17
Source File: Http2ClientLiveTest.java From tutorials with MIT License | 4 votes |
@Test public void whenRequestSent_thenHelloWorldReceived() throws Exception { EventLoopGroup workerGroup = new NioEventLoopGroup(); Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE, HOST, PORT); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(initializer); channel = b.connect() .syncUninterruptibly() .channel(); logger.info("Connected to [" + HOST + ':' + PORT + ']'); Http2SettingsHandler http2SettingsHandler = initializer.getSettingsHandler(); http2SettingsHandler.awaitSettings(60, TimeUnit.SECONDS); logger.info("Sending request(s)..."); FullHttpRequest request = Http2Util.createGetRequest(HOST, PORT); Http2ClientResponseHandler responseHandler = initializer.getResponseHandler(); int streamId = 3; responseHandler.put(streamId, channel.write(request), channel.newPromise()); channel.flush(); String response = responseHandler.awaitResponses(60, TimeUnit.SECONDS); assertEquals("Hello World", response); logger.info("Finished HTTP/2 request(s)"); } finally { workerGroup.shutdownGracefully(); } }
Example 18
Source File: MqttClientImpl.java From smartacus-mqtt-broker with Apache License 2.0 | 4 votes |
private Future<MqttConnectResult> connect(String host, int port, boolean reconnect) { if (this.eventLoop == null) { this.eventLoop = new NioEventLoopGroup(); } this.host = host; this.port = port; Promise<MqttConnectResult> connectFuture = new DefaultPromise<>(this.eventLoop.next()); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(this.eventLoop); bootstrap.channel(clientConfig.getChannelClass()); bootstrap.remoteAddress(host, port); bootstrap.handler(new MqttChannelInitializer(connectFuture, host, port, clientConfig.getSslContext())); ChannelFuture future = bootstrap.connect(); future.addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { MqttClientImpl.this.channel = f.channel(); MqttClientImpl.this.channel.closeFuture().addListener((ChannelFutureListener) channelFuture -> { if (isConnected()) { return; } ChannelClosedException e = new ChannelClosedException("Channel is closed!"); if (callback != null) { callback.connectionLost(e); } pendingSubscriptions.clear(); serverSubscriptions.clear(); subscriptions.clear(); pendingServerUnsubscribes.clear(); qos2PendingIncomingPublishes.clear(); pendingPublishes.clear(); pendingSubscribeTopics.clear(); handlerToSubscribtion.clear(); publish("TEST_TOPIC", Unpooled.wrappedBuffer("测试消息".getBytes())); scheduleConnectIfRequired(host, port, true); }); } else { scheduleConnectIfRequired(host, port, reconnect); } }); return connectFuture; }
Example 19
Source File: PeerClient.java From ethereumj with MIT License | 4 votes |
public void connect(String host, int port) { EventLoopGroup workerGroup = new NioEventLoopGroup(); if (peerListener != null) peerListener.console("Connecting to: " + host + ":" + port); p2pHandler = new P2pHandler(msgQueue, peerListener, peerDiscoveryMode); p2pHandler.activate(); ethHandler = new EthHandler(msgQueue, peerListener, peerDiscoveryMode); shhHandler = new ShhHandler(msgQueue, peerListener); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONFIG.peerConnectionTimeout()); b.remoteAddress(host, port); b.handler(new ChannelInitializer<NioSocketChannel>() { @Override public void initChannel(NioSocketChannel ch) throws Exception { ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(CONFIG.peerChannelReadTimeout(), TimeUnit.SECONDS)); ch.pipeline().addLast("out encoder", new MessageEncoder()); ch.pipeline().addLast("in encoder", new MessageDecoder()); ch.pipeline().addLast(Capability.P2P , p2pHandler); ch.pipeline().addLast(Capability.ETH, ethHandler); ch.pipeline().addLast(Capability.SHH, shhHandler); // limit the size of receiving buffer to 1024 ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(32368)); ch.config().setOption(ChannelOption.SO_RCVBUF, 32368); } }); // Start the client. ChannelFuture f = b.connect().sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); logger.debug("Connection is closed"); } catch (Exception e) { logger.debug("Exception: {} ({})", e.getMessage(), e.getClass().getName()); throw new Error("Disconnnected"); } finally { workerGroup.shutdownGracefully(); p2pHandler.killTimers(); /* final Set<PeerData> peers = WorldManager.getInstance().getPeerDiscovery().getPeers(); synchronized (peers) { for (PeerData peer : peers) { if (host.equals(peer.getAddress().getHostAddress()) && port == peer.getPort()) peer.setOnline(false); } } */ } }
Example 20
Source File: NettyServerManager.java From anetty_client with Apache License 2.0 | 4 votes |
/** * 连接方法 * * @param host * @param port * @throws Exception */ @SuppressWarnings("rawtypes") public void connect(final String host, final int port, final INettyHandlerListener connectionListener) throws Exception { Log.i(getClass().getName(), "connect come in!connectState=" + connectState); if (isConnected() || connectState == CONNECT_PROCESSORING) { // 連接成功 停止重连 NettyAlarmManager.stopReconnection(); return; } Log.i(getClass().getName(), "connect come in!CONNECT_PROCESSORING!"); connectState = CONNECT_PROCESSORING; mHost = host; mPort = port; System.setProperty("java.net.preferIPv4Stack", "true"); System.setProperty("java.net.preferIPv6Addresses", "false"); ChannelFuture channelFuture = null; group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.TCP_NODELAY, true); b.remoteAddress(new InetSocketAddress(mHost, mPort)); // 有连接到达时会创建一个channel final ExtensionRegistry registry = ExtensionRegistry.newInstance(); CommandProtoc.registerAllExtensions(registry); b.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder()); pipeline.addLast("protobufDecoder", new ProtobufDecoder(CommandProtoc.PushMessage.getDefaultInstance(), registry)); pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast("protobufEncoder", new ProtobufEncoder()); pipeline.addLast(new PushMessageHandler(connectionManager, mNettyProcessorHandler)); } }); channelFuture = b.connect().sync(); channelFuture.addListener(new ChannelFutureListener() { @SuppressWarnings("unchecked") public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { SocketAddress sa = future.channel().remoteAddress(); if(sa!=null){ Log.i(getClass().getName(), "netty server connected success! host:" + sa); // 連接成功 connectState = CONNECT_SUCCESS; if (connectionListener != null) { connectionListener.callback(null); } // 启动心跳程序 NettyAlarmManager.startHeart(mContext); // 連接成功 停止重连 NettyAlarmManager.stopReconnection(); }else{ Log.i(getClass().getName(), "netty server connected failed! host:" + sa); // 連接失敗 connectState = CONNECT_FAILED; // 連接 失敗 啟動重連 future.cause().printStackTrace(); future.channel().close(); } } else { Log.i(getClass().getName(), "netty server attemp failed! host:" + future.channel().remoteAddress()); // 連接失敗 connectState = CONNECT_FAILED; // 連接 失敗 啟動重連 future.cause().printStackTrace(); future.channel().close(); // NettyAlarmManager.startReconnection(mContext); // if (mNetworkCallback != null) { // mNetworkCallback.connectFailed(); // } } } }); // Wait until the connection is closed. // channelFuture.channel().closeFuture().sync(); } catch (Exception e) { Log.i(getClass().getName(), e.getMessage()); connectState = CONNECT_EXCEPTION; // 连接关闭后启动重连 NettyAlarmManager.startReconnection(mContext); } finally { Log.i(getClass().getName(), "connect finally!connectState=" + connectState); disconnect(channelFuture); } }