use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project scalecube by scalecube.
the class TransportImpl method bind0.
/**
* Helper bind method to start accepting connections on {@code listenAddress} and {@code bindPort}.
*
* @param bindPort bind port.
* @param finalBindPort maximum port to bind.
* @throws NoSuchElementException if {@code bindPort} greater than {@code finalBindPort}.
* @throws IllegalArgumentException if {@code bindPort} doesnt belong to the range [{@link Addressing#MIN_PORT_NUMBER}
* .. {@link Addressing#MAX_PORT_NUMBER}].
*/
private CompletableFuture<Transport> bind0(ServerBootstrap server, InetAddress listenAddress, int bindPort, int finalBindPort) {
incomingMessagesSubject.subscribeOn(Schedulers.from(bootstrapFactory.getWorkerGroup()));
final CompletableFuture<Transport> result = new CompletableFuture<>();
// Perform basic bind port validation
if (bindPort < MIN_PORT_NUMBER || bindPort > MAX_PORT_NUMBER) {
result.completeExceptionally(new IllegalArgumentException("Invalid port number: " + bindPort));
return result;
}
if (bindPort > finalBindPort) {
result.completeExceptionally(new NoSuchElementException("Could not find an available port from: " + bindPort + " to: " + finalBindPort));
return result;
}
// Get address object and bind
address = Address.create(listenAddress.getHostAddress(), bindPort);
ChannelFuture bindFuture = server.bind(listenAddress, address.port());
bindFuture.addListener((ChannelFutureListener) channelFuture -> {
if (channelFuture.isSuccess()) {
serverChannel = (ServerChannel) channelFuture.channel();
networkEmulator = new NetworkEmulator(address, config.isUseNetworkEmulator());
networkEmulatorHandler = config.isUseNetworkEmulator() ? new NetworkEmulatorHandler(networkEmulator) : null;
LOGGER.info("Bound to: {}", address);
result.complete(TransportImpl.this);
} else {
Throwable cause = channelFuture.cause();
if (config.isPortAutoIncrement() && isAddressAlreadyInUseException(cause)) {
LOGGER.warn("Can't bind to address {}, try again on different port [cause={}]", address, cause.toString());
bind0(server, listenAddress, bindPort + 1, finalBindPort).thenAccept(result::complete);
} else {
LOGGER.error("Failed to bind to: {}, cause: {}", address, cause);
result.completeExceptionally(cause);
}
}
});
return result;
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project scalecube by scalecube.
the class TransportImpl method connect.
private ChannelFuture connect(Address address) {
OutgoingChannelInitializer channelInitializer = new OutgoingChannelInitializer(address);
Bootstrap client = bootstrapFactory.clientBootstrap().handler(channelInitializer);
ChannelFuture connectFuture = client.connect(address.host(), address.port());
// Register logger and cleanup listener
connectFuture.addListener((ChannelFutureListener) channelFuture -> {
if (channelFuture.isSuccess()) {
LOGGER.debug("Connected from {} to {}: {}", TransportImpl.this.address, address, channelFuture.channel());
} else {
LOGGER.warn("Failed to connect from {} to {}", TransportImpl.this.address, address);
outgoingChannels.remove(address);
}
});
return connectFuture;
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project scalecube by scalecube.
the class NettyServerTransport method bind0.
private CompletableFuture<NettyServerTransport> bind0(InetAddress bindAddress, int bindPort, int finalBindPort) {
CompletableFuture<NettyServerTransport> result = new CompletableFuture<>();
// Perform basic bind port validation
if (bindPort < MIN_PORT_NUMBER || bindPort > MAX_PORT_NUMBER) {
result.completeExceptionally(new IllegalArgumentException("Invalid port number: " + bindPort));
return result;
}
if (bindPort > finalBindPort) {
result.completeExceptionally(new NoSuchElementException("Could not find an available port from: " + bindPort + " to: " + finalBindPort));
return result;
}
// Start binding
ChannelFuture bindFuture = serverBootstrap.bind(bindAddress, bindPort);
bindFuture.addListener((ChannelFutureListener) channelFuture -> {
if (channelFuture.isSuccess()) {
NettyServerTransport.this.init(bindAddress, bindPort, (ServerChannel) channelFuture.channel());
result.complete(NettyServerTransport.this);
} else {
Throwable cause = channelFuture.cause();
if (config.isPortAutoIncrement() && isAddressAlreadyInUseException(cause)) {
bind0(bindAddress, bindPort + 1, finalBindPort).thenAccept(result::complete);
} else {
result.completeExceptionally(cause);
}
}
});
return result;
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project alien4cloud by alien4cloud.
the class StompConnection method init.
@SneakyThrows({ InterruptedException.class, URISyntaxException.class })
private void init() {
if (this.stompChannel != null) {
throw new IllegalStateException("The stomp connection has already been started");
}
String wsUrl = "ws://" + host + ":" + port + endPoint + "/websocket";
if (log.isDebugEnabled()) {
log.debug("Web socket url {}", wsUrl);
}
String loginUrl = null;
if (user != null && password != null && loginPath != null) {
loginUrl = "http://" + host + ":" + port + loginPath;
if (log.isDebugEnabled()) {
log.debug("Authentication url {}", loginUrl);
}
}
this.eventLoopGroup = new NioEventLoopGroup();
this.stompClientHandler = new StompClientHandler();
DefaultHttpHeaders handshakeHeaders = new DefaultHttpHeaders();
if (this.headers != null) {
for (Map.Entry<String, String> header : this.headers.entrySet()) {
handshakeHeaders.add(header.getKey(), header.getValue());
}
}
final WebSocketClientHandler webSocketHandler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(new URI(wsUrl), WebSocketVersion.V13, null, false, handshakeHeaders), host, user, password, loginUrl);
Bootstrap b = new Bootstrap();
b.group(eventLoopGroup).channel(NioSocketChannel.class);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(HttpClientCodec.class.getName(), new HttpClientCodec());
pipeline.addLast(HttpObjectAggregator.class.getName(), new HttpObjectAggregator(8192));
pipeline.addLast(WebSocketClientCompressionHandler.class.getName(), new WebSocketClientCompressionHandler());
pipeline.addLast(WebSocketClientHandler.class.getName(), webSocketHandler);
pipeline.addLast(StompSubframeDecoder.class.getName(), new StompSubframeDecoder());
pipeline.addLast(StompSubframeEncoder.class.getName(), new StompSubframeEncoder());
pipeline.addLast(StompSubframeAggregator.class.getName(), new StompSubframeAggregator(1048576));
pipeline.addLast(StompClientHandler.class.getName(), stompClientHandler);
}
});
this.stompChannel = b.connect(host, port).sync().channel();
this.stompClientHandler.connectFuture(this.stompChannel.newPromise());
webSocketHandler.handshakeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(final ChannelFuture future) throws Exception {
stompClientHandler.beginStomp(stompChannel);
}
});
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project duangframework by tcrct.
the class RpcClient method call.
/**
* 调用运程方法
* @param request rpc请求对象,封装请求的参数,参数类型等
* @param action rpc生产者对象,封装了生产者或者说是要调用的方法的类名,方法名,IP地址,端口等
* @return 处理结果 RpcResponse对象
* @throws Exception
*/
public RpcResponse call(RpcRequest request, RpcAction action) throws Exception {
// 这里要用内网的IP地址
Channel channel = getChannel(action.getIntranetip(), action.getPort());
RpcResponse response = null;
// 先初始化一个以请求ID为KEY的响应阵列到集合中
final String requestId = request.getRequestId();
// 将请求结果预存到MAP中,以请求ID为key
RESPONSE_MAP.put(requestId, new LinkedBlockingQueue<RpcResponse>(1));
try {
if (channel.isOpen()) {
MessageHolder<RpcRequest> messageHolder = new MessageHolder<RpcRequest>(Protocol.REQUEST, Protocol.OK, request);
ChannelFuture writeFuture = channel.writeAndFlush(messageHolder).sync();
writeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
// 如果返回正常,则直接退出
if (future.isSuccess()) {
return;
} else {
String errorMsg = "Send request[" + requestId + "] to [" + future.channel().toString() + "] is error: " + future.cause().toString();
throw new RpcException(errorMsg);
}
}
});
} else {
logger.warn("channel.isClose: " + channel.remoteAddress());
}
response = getRpcResponse(requestId, request.getTimeout());
if (null != response) {
logger.warn("poll time: " + (System.currentTimeMillis() - response.getRequestStartTime()) + " ms");
}
} catch (Exception e) {
response = createExceptionRpcResponse(action, e, requestId);
} finally {
// 无论成功与否,都必须移除集合中指定KEY的队列
RESPONSE_MAP.remove(requestId);
}
return response;
}
Aggregations