本文整理匯總了Java中org.jboss.netty.channel.ChannelFuture.getChannel方法的典型用法代碼示例。如果您正苦於以下問題:Java ChannelFuture.getChannel方法的具體用法?Java ChannelFuture.getChannel怎麽用?Java ChannelFuture.getChannel使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.jboss.netty.channel.ChannelFuture
的用法示例。
在下文中一共展示了ChannelFuture.getChannel方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: bootstrap
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
public boolean bootstrap(HostAndPort seed,
Node localNode) throws SyncException {
this.localNode = localNode;
succeeded = false;
SocketAddress sa =
new InetSocketAddress(seed.getHostText(), seed.getPort());
ChannelFuture future = bootstrap.connect(sa);
future.awaitUninterruptibly();
if (!future.isSuccess()) {
logger.debug("Could not connect to " + seed, future.getCause());
return false;
}
Channel channel = future.getChannel();
logger.debug("[{}] Connected to {}",
localNode != null ? localNode.getNodeId() : null,
seed);
try {
channel.getCloseFuture().await();
} catch (InterruptedException e) {
logger.debug("Interrupted while waiting for bootstrap");
return succeeded;
}
return succeeded;
}
示例2: connect
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
protected boolean connect(String hostname, int port) {
ready = false;
if (channel == null || !channel.isConnected()) {
SocketAddress sa =
new InetSocketAddress(hostname, port);
ChannelFuture future = clientBootstrap.connect(sa);
future.awaitUninterruptibly();
if (!future.isSuccess()) {
logger.error("Could not connect to " + hostname +
":" + port, future.getCause());
return false;
}
channel = future.getChannel();
}
while (!ready && channel != null && channel.isConnected()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
if (!ready || channel == null || !channel.isConnected()) {
logger.warn("Timed out connecting to {}:{}", hostname, port);
return false;
}
logger.debug("Connected to {}:{}", hostname, port);
return true;
}
示例3: bindToPrivilegedPort
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
/**
* This attempts to bind to privileged ports, starting with 1023 and working downwards, and returns when the first binding succeeds.
*
* <p>
* Some NFS servers apparently may require that some requests originate on
* an Internet port below IPPORT_RESERVED (1024). This is generally not
* used, though, as the client then has to run as a user authorized for
* privileged, which is dangerous. It is also not generally needed.
* </p>
*
* @return
* <ul>
* <li><code>true</code> if the binding succeeds,</li>
* <li><code>false</code> otherwise.</li>
* </ul>
* @throws RpcException If an exception occurs, or if no binding succeeds.
*/
private Channel bindToPrivilegedPort() throws RpcException {
System.out.println("Attempting to use privileged port.");
for (int port = 1023; port > 0; --port) {
try {
ChannelPipeline pipeline = _clientBootstrap.getPipelineFactory().getPipeline();
Channel channel = _clientBootstrap.getFactory().newChannel(pipeline);
channel.getConfig().setOptions(_clientBootstrap.getOptions());
ChannelFuture bindFuture = channel.bind(new InetSocketAddress(port)).awaitUninterruptibly();
if (bindFuture.isSuccess()) {
System.out.println("Success! Bound to port " + port);
return bindFuture.getChannel();
}
} catch (Exception e) {
String msg = String.format("rpc request bind error for address: %s",
getRemoteAddress());
throw new RpcException(RpcStatus.NETWORK_ERROR, msg, e);
}
}
throw new RpcException(RpcStatus.LOCAL_BINDING_ERROR, String.format("Cannot bind a port < 1024: %s", getRemoteAddress()));
}
示例4: connect
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
/**
* 嘗試連接
*/
public void connect() {
ChannelFuture future = bootstrap.connect(inetAddr);
try{
boolean ret = future.awaitUninterruptibly(Constants.TIMEOUT_CONNECTION_MILLSECOND, TimeUnit.MILLISECONDS);
if (ret && future.isSuccess()) {
Channel newChannel = future.getChannel();
newChannel.setInterestOps(Channel.OP_READ_WRITE);
try {
// 關閉舊的連接
Channel oldChannel = NettyRpcConnection.this.channel;
if (oldChannel != null) {
logger.info("Close old netty channel {} on create new netty channel {}", oldChannel, newChannel);
oldChannel.close();
}
} finally {
if (!isConnected()) {
try {
logger.info("Close new netty channel {}, because the client closed.", newChannel);
newChannel.close();
} finally {
NettyRpcConnection.this.channel = null;
}
} else {
NettyRpcConnection.this.channel = newChannel;
}
}
} else if (null != future.getCause()) {
logger.error("connect fail", future.getCause());
throw new RuntimeException("connect error", future.getCause());
} else {
logger.error("connect fail,connstr: "+this.getConnStr());
throw new RuntimeException("connect error");
}
}finally{
if (! isConnected()) {
future.cancel();
}
}
}
示例5: connectToChannelsLight
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
protected NodeChannels connectToChannelsLight(DiscoveryNode node) {
InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address();
ChannelFuture connect = clientBootstrap.connect(address);
connect.awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
if (!connect.isSuccess()) {
throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connect.getCause());
}
Channel[] channels = new Channel[1];
channels[0] = connect.getChannel();
channels[0].getCloseFuture().addListener(new ChannelCloseListener(node));
return new NodeChannels(channels, channels, channels, channels, channels);
}
示例6: TSOClientRaw
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
public TSOClientRaw(String host, int port) throws InterruptedException, ExecutionException {
// Start client with Nb of active threads = 3 as maximum.
ChannelFactory factory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()), 3);
// Create the bootstrap
ClientBootstrap bootstrap = new ClientBootstrap(factory);
InetSocketAddress addr = new InetSocketAddress(host, port);
ChannelPipeline pipeline = bootstrap.getPipeline();
pipeline.addLast("lengthbaseddecoder",
new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
pipeline.addLast("protobufdecoder",
new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
pipeline.addLast("protobufencoder", new ProtobufEncoder());
Handler handler = new Handler();
pipeline.addLast("handler", handler);
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);
bootstrap.setOption("reuseAddress", true);
bootstrap.setOption("connectTimeoutMillis", 100);
ChannelFuture channelFuture = bootstrap.connect(addr).await();
channel = channelFuture.getChannel();
}
示例7: testNettyChannelWriting
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
@Test(timeOut = 10_000)
public void testNettyChannelWriting() throws Exception {
// ------------------------------------------------------------------------------------------------------------
// Prepare test
// ------------------------------------------------------------------------------------------------------------
// Connect channel handler
channelHandler.reconnect();
// Create client and connect it
ClientBootstrap nettyClient = createNettyClientBootstrap();
ChannelFuture channelF = nettyClient.connect(new InetSocketAddress("localhost", 1434));
// Basic checks for connection
while (!channelF.isDone()) /** do nothing */ ;
assertTrue(channelF.isSuccess());
assertTrue(channelF.getChannel().isConnected());
Channel channel = channelF.getChannel();
// Eventually the channel group of the server should have 2 elements
while (channelHandler.channelGroup.size() != 2) /** do nothing */ ;
// Write first handshake request
TSOProto.HandshakeRequest.Builder handshake = TSOProto.HandshakeRequest.newBuilder();
// NOTE: Add here the required handshake capabilities when necessary
handshake.setClientCapabilities(TSOProto.Capabilities.newBuilder().build());
channelF.getChannel().write(TSOProto.Request.newBuilder().setHandshakeRequest(handshake.build()).build());
// ------------------------------------------------------------------------------------------------------------
// Test channel writing
// ------------------------------------------------------------------------------------------------------------
testWritingTimestampRequest(channel);
testWritingCommitRequest(channel);
testWritingFenceRequest(channel);
}
示例8: doExecute
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public <R extends ActionRequest, T extends ActionResponse, B extends ActionRequestBuilder<R, T, B>>
void doExecute(Action<R, T, B> action, R request, ActionListener<T> listener) {
HttpAction httpAction = actionMap.get(action);
if (httpAction == null) {
throw new IllegalStateException("failed to find http action [" + action + "] to execute");
}
try {
HttpContext httpContext = new HttpContext(httpAction, listener, request);
httpContext.httpRequest = httpAction.createHttpRequest(url, request);
ChannelFuture future = bootstrap.connect(new InetSocketAddress(url.getHost(), url.getPort()));
future.awaitUninterruptibly();
if (!future.isSuccess()) {
bootstrap.releaseExternalResources();
logger.error("can't connect to {}", url);
} else {
Channel channel = future.getChannel();
httpContext.setChannel(channel);
httpContextMap.put(channel, httpContext);
channel.getConfig().setConnectTimeoutMillis(settings.getAsInt("http.client.timeout", 5000));
httpAction.execute(httpContext, listener);
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
示例9: connect
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
public void connect(){
bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setOption("tcpNoDelay", false);
bootstrap.setOption("keepAlive", true);
final NettyClientHandler handler = new NettyClientHandler(this, timer);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("handler", handler);
pipeline.addLast("encoder", new StringEncoder());
return pipeline;
}
});
bootstrap.setOption("remoteAddress", new InetSocketAddress(host, port));
try {
ChannelFuture future = bootstrap.connect().sync();
channel = future.getChannel();
} catch (Exception e) {
logger.error(ExceptionUtil.getErrorMessage(e));
bootstrap.releaseExternalResources();
System.exit(-1);//第一次連接出現異常直接退出,不走重連
}
}
示例10: openChannel
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
// blocking for channel to be done
if (LOG.isTraceEnabled()) {
LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture, configuration.getConnectTimeout());
}
// here we need to wait it in other thread
final CountDownLatch channelLatch = new CountDownLatch(1);
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture cf) throws Exception {
channelLatch.countDown();
}
});
try {
channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
throw new CamelException("Interrupted while waiting for " + "connection to "
+ configuration.getAddress());
}
if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
if (channelFuture.getCause() != null) {
cause.initCause(channelFuture.getCause());
}
throw cause;
}
Channel answer = channelFuture.getChannel();
if (LOG.isDebugEnabled()) {
LOG.debug("Creating connector to address: {}", configuration.getAddress());
}
return answer;
}
示例11: openChannel
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
// blocking for channel to be done
if (LOG.isTraceEnabled()) {
LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture, configuration.getConnectTimeout());
}
// here we need to wait it in other thread
final CountDownLatch channelLatch = new CountDownLatch(1);
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture cf) throws Exception {
channelLatch.countDown();
}
});
try {
channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
throw new CamelException("Interrupted while waiting for " + "connection to "
+ configuration.getAddress());
}
if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
if (channelFuture.getCause() != null) {
cause.initCause(channelFuture.getCause());
}
throw cause;
}
Channel answer = channelFuture.getChannel();
// to keep track of all channels in use
allChannels.add(answer);
if (LOG.isDebugEnabled()) {
LOG.debug("Creating connector to address: {}", configuration.getAddress());
}
return answer;
}
示例12: doConnect
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
protected void doConnect() throws Throwable {
long start = System.currentTimeMillis();
ChannelFuture future = bootstrap.connect(getConnectAddress());
try{
boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
if (ret && future.isSuccess()) {
Channel newChannel = future.getChannel();
newChannel.setInterestOps(Channel.OP_READ_WRITE);
try {
// 關閉舊的連接
Channel oldChannel = NettyClient.this.channel; // copy reference
if (oldChannel != null) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
}
oldChannel.close();
} finally {
NettyChannel.removeChannelIfDisconnected(oldChannel);
}
}
} finally {
if (NettyClient.this.isClosed()) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close new netty channel " + newChannel + ", because the client closed.");
}
newChannel.close();
} finally {
NettyClient.this.channel = null;
NettyChannel.removeChannelIfDisconnected(newChannel);
}
} else {
NettyClient.this.channel = newChannel;
}
}
} else if (future.getCause() != null) {
throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
+ getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
} else {
throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
+ getRemoteAddress() + " client-side timeout "
+ getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
}
}finally{
if (! isConnected()) {
future.cancel();
}
}
}
示例13: setChannel
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
public void setChannel(ChannelFuture channelfuture) {
this.channel = channelfuture.getChannel();
}
示例14: doConnect
import org.jboss.netty.channel.ChannelFuture; //導入方法依賴的package包/類
protected void doConnect() throws Throwable {
long start = System.currentTimeMillis();
ChannelFuture future = bootstrap.connect(getConnectAddress());
try{
boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
if (ret && future.isSuccess()) {
Channel newChannel = future.getChannel();
newChannel.setInterestOps(Channel.OP_READ_WRITE);
try {
// 關閉舊的連接
Channel oldChannel = NettyClient.this.channel; // copy reference
if (oldChannel != null) {
try {
if (log.isInfoEnabled()) {
log.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
}
oldChannel.close();
} finally {
NettyChannel.removeChannelIfDisconnected(oldChannel);
}
}
} finally {
if (NettyClient.this.isClosed()) {
try {
if (log.isInfoEnabled()) {
log.info("Close new netty channel " + newChannel + ", because the client closed.");
}
newChannel.close();
} finally {
NettyClient.this.channel = null;
NettyChannel.removeChannelIfDisconnected(newChannel);
}
} else {
NettyClient.this.channel = newChannel;
}
}
} else if (future.getCause() != null) {
throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
+ getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
} else {
throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
+ getRemoteAddress() + " client-side timeout "
+ getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
}
}finally{
if (! isConnected()) {
future.cancel();
}
}
}