當前位置: 首頁>>代碼示例>>Java>>正文


Java NioSocketChannel類代碼示例

本文整理匯總了Java中io.netty.channel.socket.nio.NioSocketChannel的典型用法代碼示例。如果您正苦於以下問題:Java NioSocketChannel類的具體用法?Java NioSocketChannel怎麽用?Java NioSocketChannel使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


NioSocketChannel類屬於io.netty.channel.socket.nio包,在下文中一共展示了NioSocketChannel類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: open

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的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());

            }
        });
    }
 
開發者ID:justice-code,項目名稱:star-map,代碼行數:23,代碼來源:StarClientProtocol.java

示例2: start

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的package包/類
public void start() throws InterruptedException {
	final EventLoopGroup workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup();

	try {
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(workerGroup)
				.channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class)
				.handler(new OpenCloudChannelInitializer(this))
				.connect(this.host, this.port).sync().channel().closeFuture().syncUninterruptibly();
	} catch (Exception ex) {
		if (ex.getClass().getSimpleName().equals("AnnotatedConnectException")) {
			System.err.println("Cannot connect to master!");
			channel.close();
		} else {
			ex.printStackTrace();
		}
	} finally {
		workerGroup.shutdownGracefully();
		System.out.println("Netty client stopped");
		Runtime.getRuntime().halt(0);
	}
}
 
開發者ID:CentauriCloud,項目名稱:CentauriCloud,代碼行數:23,代碼來源:Client.java

示例3: start

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的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();
	}
}
 
開發者ID:polarcoral,項目名稱:monica,代碼行數:19,代碼來源:SocketClient.java

示例4: newPool

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的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
    );
}
 
開發者ID:rodbate,項目名稱:fastdfs-spring-boot,代碼行數:19,代碼來源:FastdfsPoolGroup.java

示例5: start

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的package包/類
public void start() {
    bootstrap.group(group).channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            //                ch.pipeline().addLast(new IdleStateHandler(1, 1, 5));
            ch.pipeline().addLast(new KyroMsgDecoder());
            ch.pipeline().addLast(new KyroMsgEncoder());
            ch.pipeline().addLast(new ClientHandler());
        }
    });

    new ScheduledThreadPoolExecutor(1).scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            scanResponseTable(3000);
        }
    }, 1000, 1000, TimeUnit.MILLISECONDS);
}
 
開發者ID:lemonJun,項目名稱:TakinRPC,代碼行數:21,代碼來源:RemotingNettyClient.java

示例6: main

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的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();
            }
        }
    });
}
 
開發者ID:alamby,項目名稱:upgradeToy,代碼行數:21,代碼來源:SimpleClient.java

示例7: BinaryClient

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的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());
}
 
開發者ID:HankXV,項目名稱:Limitart,代碼行數:23,代碼來源:BinaryClient.java

示例8: connect

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的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();
}
 
開發者ID:altiplanogao,項目名稱:io-comparison,代碼行數:25,代碼來源:NettyClient.java

示例9: bootstrap

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的package包/類
private final Future<Void> bootstrap(final NettyChannel channel) {
  final Promise<Void> p = Promise.apply();
  new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
      .option(ChannelOption.SO_KEEPALIVE, true)
      .option(ChannelOption.AUTO_READ, false)
      .handler(new ChannelInitializer<io.netty.channel.Channel>() {
        @Override
        protected void initChannel(final io.netty.channel.Channel ch) throws Exception {
          ch.pipeline().addLast(new MessageDecoder(), new MessageEncoder(),
              new FlowControlHandler(), channel);
        }
      })
      .connect(new InetSocketAddress(host, port))
      .addListener(future -> p.become(Future.VOID));
  return p;
}
 
開發者ID:traneio,項目名稱:ndbc,代碼行數:17,代碼來源:ChannelSupplier.java

示例10: connectAsync

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的package包/類
public ChannelFuture connectAsync(String host, int port, String remoteId, boolean discoveryMode) {
    ethereumListener.trace("Connecting to: " + host + ":" + port);

    EthereumChannelInitializer ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, remoteId);
    ethereumChannelInitializer.setPeerDiscoveryMode(discoveryMode);

    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(ethereumChannelInitializer);

    // Start the client.
    return b.connect();
}
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:21,代碼來源:PeerClient.java

示例11: getConnection

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的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));
    }
}
 
開發者ID:airlift,項目名稱:drift,代碼行數:25,代碼來源:ConnectionFactory.java

示例12: init

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的package包/類
/**
 * 初始化連接池
 */
public void init() {
    bootstrap = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup();
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(new LoggingHandler());
    //所有的公用一個eventloopgroup, 對於客戶端來說應該問題不大!
    poolMap = new AbstractChannelPoolMap<InetSocketAddress, FixedChannelPool>() {
        @Override
        protected FixedChannelPool newPool(InetSocketAddress key) {
            return new FixedChannelPool(bootstrap.remoteAddress(key), new FixedChannelPoolHandler(), 2);
        }
    };
    //預先建立好鏈接
    serverListConfig.getAddressList().stream().forEach(address -> {
        poolMap.get(address);
    });
}
 
開發者ID:recklessMo,項目名稱:nettyRpc,代碼行數:23,代碼來源:ClientConnectionPool.java

示例13: run

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的package包/類
public void run() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(host, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });
        ChannelFuture f = b.connect().sync();
        f.channel().closeFuture().sync();

    } finally {
        group.shutdownGracefully().sync();
    }
}
 
開發者ID:oes-network,項目名稱:im,代碼行數:21,代碼來源:EchoClient.java

示例14: connectAsync

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的package包/類
public ChannelFuture connectAsync(String host, int port, String remoteId, boolean discoveryMode) {
    ethereumListener.trace("Connecting to: " + host + ":" + port);

    EthereumChannelInitializer ethereumChannelInitializer = ethereumChannelInitializerFactory.newInstance(remoteId);
    ethereumChannelInitializer.setPeerDiscoveryMode(discoveryMode);

    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(ethereumChannelInitializer);

    // Start the client.
    return b.connect();
}
 
開發者ID:rsksmart,項目名稱:rskj,代碼行數:21,代碼來源:PeerClient.java

示例15: start

import io.netty.channel.socket.nio.NioSocketChannel; //導入依賴的package包/類
public void start(String hostName, int port) {
    Executors.newSingleThreadExecutor().submit(() -> {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new KyChannelInitializer());
        if (hostName != null && !hostName.equals(""))
            bootstrap.remoteAddress(new InetSocketAddress(hostName, port));
        else
            bootstrap.remoteAddress(new InetSocketAddress(port));
        ChannelFuture channelFuture = null;

        try {
            channelFuture = bootstrap.connect().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        startListenerHandle(channelFuture, launchListener);
    });
}
 
開發者ID:bitkylin,項目名稱:ClusterDeviceControlPlatform,代碼行數:23,代碼來源:NettyClient.java


注:本文中的io.netty.channel.socket.nio.NioSocketChannel類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。