本文整理汇总了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());
}
});
}
示例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);
}
}
示例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();
}
}
示例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
);
}
示例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);
}
示例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();
}
}
});
}
示例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());
}
示例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();
}
示例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;
}
示例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();
}
示例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));
}
}
示例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);
});
}
示例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();
}
}
示例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();
}
示例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);
});
}