本文整理汇总了Java中io.netty.channel.ChannelFuture类的典型用法代码示例。如果您正苦于以下问题:Java ChannelFuture类的具体用法?Java ChannelFuture怎么用?Java ChannelFuture使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ChannelFuture类属于io.netty.channel包,在下文中一共展示了ChannelFuture类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: completable
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
/**
* Convenience method to convert a {@link ChannelFuture} into a {@link CompletableFuture}
*
* @param future future to convert.
* @return converted future.
*/
public static CompletableFuture<Void> completable(ChannelFuture future) {
CompletableFuture<Void> cf = new CompletableFuture<>();
future.addListener(
(ChannelFutureListener)
future1 -> {
if (future1.isSuccess()) {
cf.complete(null);
} else {
cf.completeExceptionally(future1.cause());
}
});
return cf;
}
示例2: writeBack
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
public static int writeBack(Channel channel, boolean isSuccess, String resultStr, boolean isKeepAlive) {
ByteBuf content = Unpooled.copiedBuffer(resultStr, Constants.DEFAULT_CHARSET);
HttpResponseStatus status;
if (isSuccess) {
status = HttpResponseStatus.OK;
} else {
status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
}
FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content);
//logger.info("result str:{}", resultStr);
res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
HttpHeaders.setContentLength(res, content.readableBytes());
try {
ChannelFuture f = channel.writeAndFlush(res);
if (isKeepAlive) {
HttpHeaders.setKeepAlive(res, true);
} else {
HttpHeaders.setKeepAlive(res, false);//set keepalive closed
f.addListener(ChannelFutureListener.CLOSE);
}
} catch (Exception e2) {
logger.warn("Failed to send HTTP response to remote, cause by:", e2);
}
return content.readableBytes();
}
示例3: connect
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
/**
* Connects to the node and returns only upon connection close
*/
public void connect(String host, int port, String remoteId, boolean discoveryMode) {
try {
ChannelFuture f = connectAsync(host, port, remoteId, discoveryMode);
f.sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
logger.debug("Connection is closed");
} catch (Exception e) {
if (discoveryMode) {
logger.trace("Exception:", e);
} else {
if (e instanceof IOException) {
logger.info("PeerClient: Can't connect to " + host + ":" + port + " (" + e.getMessage() + ")");
logger.debug("PeerClient.connect(" + host + ":" + port + ") exception:", e);
} else {
logger.error("Exception:", e);
}
}
}
}
示例4: rebind
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
/**
* Reopens the listening channel for this node. If the channel was already open, has no effect and
* future completes immediately.
*
* @return future that completes when listening channel is reopened.
*/
private CompletableFuture<Void> rebind() {
if (this.channel.get().isOpen()) {
// already accepting...
return CompletableFuture.completedFuture(null);
}
CompletableFuture<Void> future = new CompletableFuture<>();
ChannelFuture bindFuture = bootstrap.bind(this.getAddress());
bindFuture.addListener(
(ChannelFutureListener)
channelFuture -> {
if (channelFuture.isSuccess()) {
channelFuture.channel().attr(Server.HANDLER).set(this);
logger.debug("Bound {} to {}", BoundNode.this, channelFuture.channel());
future.complete(null);
channel.set(channelFuture.channel());
} else {
// If failed, propagate it.
future.completeExceptionally(
new BindNodeException(BoundNode.this, getAddress(), channelFuture.cause()));
}
});
return future;
}
示例5: addLocalEndpoint
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
/**
* Adds a channel that listens locally
*/
public SocketAddress addLocalEndpoint()
{
ChannelFuture channelfuture;
synchronized (this.endpoints)
{
channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
{
protected void initChannel(Channel p_initChannel_1_) throws Exception
{
NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
NetworkSystem.this.networkManagers.add(networkmanager);
p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
}
}).group((EventLoopGroup)SERVER_NIO_EVENTLOOP.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
this.endpoints.add(channelfuture);
}
return channelfuture.channel().localAddress();
}
示例6: addLocalEndpoint
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
/**
* Adds a channel that listens locally
*/
public SocketAddress addLocalEndpoint()
{
ChannelFuture channelfuture;
synchronized (this.endpoints)
{
channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
{
protected void initChannel(Channel p_initChannel_1_) throws Exception
{
NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
NetworkSystem.this.networkManagers.add(networkmanager);
p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
}
}).group((EventLoopGroup)eventLoops.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
this.endpoints.add(channelfuture);
}
return channelfuture.channel().localAddress();
}
示例7: setupWithTest
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
/**
* Establishes a new socket connection with connection test
*/
protected void setupWithTest() {
ChannelFuture future = boot.connect(uri.host(), port);
future.addListener(
new GenericFutureListener<ChannelFuture>() {
public void operationComplete(ChannelFuture f) {
if (f.isSuccess()) {
channel = (HTTPChannel) f.channel();
testConnection();
onTestBell.promise(onConnectBell);
} else {
onConnectBell.ring(f.cause());
}
}
});
}
示例8: terminateEndpoints
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
/**
* Shuts down all open endpoints (with immediate effect?)
*/
public void terminateEndpoints()
{
this.isAlive = false;
for (ChannelFuture channelfuture : this.endpoints)
{
try
{
channelfuture.channel().close().sync();
}
catch (InterruptedException var4)
{
logger.error("Interrupted whilst closing channel");
}
}
}
示例9: terminateEndpoints
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
/**
* Shuts down all open endpoints (with immediate effect?)
*/
public void terminateEndpoints()
{
this.isAlive = false;
for (ChannelFuture channelfuture : this.endpoints)
{
try
{
channelfuture.channel().close().sync();
}
catch (InterruptedException var4)
{
LOGGER.error("Interrupted whilst closing channel");
}
}
}
示例10: write
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
@Override
public ProtocolFuture write(byte[] data) {
this.lastActive = System.currentTimeMillis();
if (!isClosed()) {
ChannelFuture future = channel.write(data);
return new ProtocolFuture() {
@Override
public boolean isSuccess() {
return future.isSuccess();
}
@Override
public boolean isDone() {
return future.isDone();
}
};
} else {
return ProtocolFuture.ERRORFUTURE;
}
}
示例11: channelRead
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
String sentData = in.toString(CharsetUtil.UTF_8);
String returnee = sentData + "-::=::-" + "{}";
RequestProcessor reprocessor = EchoServer.process(sentData);
if (reprocessor != null)
returnee = sentData + "-::=::-" + reprocessor.getProcessedData();
ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer(returnee, CharsetUtil.UTF_8)).sync();
if (!f.isSuccess())
try {
throw f.cause();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
示例12: main
import io.netty.channel.ChannelFuture; //导入依赖的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();
}
}
});
}
示例13: sendHttpResponse
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
private static void sendHttpResponse(ChannelHandlerContext ctx,
HttpRequest req, FullHttpResponse res) {
// Generate an error page if response getStatus code is not OK (200).
if (res.getStatus().code() != 200) {
ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
CharsetUtil.UTF_8);
res.content().writeBytes(buf);
buf.release();
setContentLength(res, res.content().readableBytes());
}
// Send the response and close the connection if necessary.
ChannelFuture f = ctx.writeAndFlush(res);
if (!isKeepAlive(req) || res.getStatus().code() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
示例14: bindAddress
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
private TransportAddress bindAddress(final InetAddress hostAddress) {
final AtomicReference<Exception> lastException = new AtomicReference<>();
final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>();
boolean success = port.iterate(portNumber -> {
try {
synchronized (serverChannels) {
ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber)).sync();
serverChannels.add(future.channel());
boundSocket.set((InetSocketAddress) future.channel().localAddress());
}
} catch (Exception e) {
lastException.set(e);
return false;
}
return true;
});
if (!success) {
throw new BindHttpException("Failed to bind to [" + port.getPortRangeString() + "]", lastException.get());
}
if (logger.isDebugEnabled()) {
logger.debug("Bound http to address {{}}", NetworkAddress.format(boundSocket.get()));
}
return new TransportAddress(boundSocket.get());
}
示例15: start
import io.netty.channel.ChannelFuture; //导入依赖的package包/类
public void start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(this.host, this.port))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("connected server...");
ch.pipeline().addLast(new ByteArrayEncoder());
ch.pipeline().addLast(new ByteArrayDecoder());
ch.pipeline().addLast(new EchoClientHandler());
}
});
ChannelFuture cf = b.connect().sync();
cf.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
}