当前位置: 首页>>代码示例>>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;未经允许,请勿转载。