List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:org.royaldev.enterprise.proxy.ProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new ProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); outboundChannel = f.channel();//from www . j a va 2 s . c o m f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }
From source file:org.scache.network.server.TransportRequestHandler.java
License:Apache License
/** * Responds to a single message with some Encodable object. If a failure occurs while sending, * it will be logged and the channel closed. *//* w w w . j a va2 s. com*/ private void respond(final Encodable result) { final String remoteAddress = channel.remoteAddress().toString(); channel.writeAndFlush(result).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { logger.trace(String.format("Sent result %s to client %s", result, remoteAddress)); } else { logger.error(String.format("Error sending result %s to %s; closing connection", result, remoteAddress), future.cause()); channel.close(); } } }); }
From source file:org.shelloid.vpt.rms.server.VPTServerHandler.java
License:Open Source License
private void handleHttpRequest(ChannelHandlerContext ctx, final FullHttpRequest req) { if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); } else if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); } else {/*from w ww . ja v a 2 s .co m*/ if (Configurations.WEBSOCKET_PATH.equals(req.getUri())) { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(req), null, false, ShelloidUtil.getMaxFrameSize()); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); Platform.shelloidLogger.warn("Client connection rejected."); } else { final Channel ch = ctx.channel(); if (verifyConnection(ch, req.headers())) { handshaker.handshake(ch, req).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { try { if (future.isSuccess()) { Boolean resetLastSendAck = Boolean.parseBoolean( req.headers().get(ShelloidHeaderFields.resetLastSendAck)); handleValidationComplete(ch, req.headers().get(ShelloidHeaderFields.version), resetLastSendAck); } else { Platform.shelloidLogger.warn("Agent authentication failed!"); ch.close(); } } catch (Exception ex) { Platform.shelloidLogger.error("Error :" + ex.getMessage(), ex); ch.close(); } } }); } else { Platform.shelloidLogger.error("Rejecting agent client connection due to auth failure: " + req.headers().get(ShelloidHeaderFields.key) + ":" + req.headers().get(ShelloidHeaderFields.secret)); WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ch); ctx.close(); } } } else { processHttpRequest(ctx, req); } } }
From source file:org.spongepowered.clean.network.NetworkConnection.java
License:MIT License
public void update() { this.timeout++; if (this.conn_state == ConnectionState.COMPLETE_LOGIN) { if (this.uid == null) { // offline mode this.uid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + this.name).getBytes(Charsets.UTF_8)); }//from w w w.ja v a 2s.c o m // TODO check bans // TODO check whitelist // TODO check server full int compress_threshold = ((SServer) Sponge.getServer()) .getServerProperties().network_compression_threshold; if (compress_threshold > 0) { sendPacket(new SetCompressionPacket(compress_threshold)).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { NetworkConnection.this.channel.pipeline().addBefore("decoder", "decompressor", new PacketDecompressor()); NetworkConnection.this.channel.pipeline().addBefore("encoder", "compressor", new PacketCompressor(compress_threshold)); } }); } sendPacket(new LoginSuccessPacket(this.uid, this.name)); changeState(ProtocolState.PLAY); this.conn_state = ConnectionState.JOINING; SGame.getLogger().info("Player [" + this.name + "] joining to world \"" + Sponge.getServer().getDefaultWorldName() + "\""); SWorld world = (SWorld) Sponge.getServer().getWorld(Sponge.getServer().getDefaultWorldName()).get(); this.player = new SPlayer(world, this.uid, this); world.addJoiningPlayer(this.player); } else if (this.conn_state == ConnectionState.PLAYING) { // if (this.timeout == 15) { // int val = (int) System.currentTimeMillis(); // sendPacket(new KeepAlivePacket(val)); // } Packet packet = this.queue.poll(); while (packet != null) { InboundPackets type = InboundPackets.get(this.state, packet.id); type.getHandler().accept(packet, this); packet = this.queue.poll(); } } // TODO timeout if too long authenticating }
From source file:org.springframework.cloud.stream.app.netty.tcp.source.NettyTcpReceivingChannelAdapter.java
License:Apache License
@Override protected void onInit() { super.onInit(); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override// ww w .j a v a2 s .c o m protected void initChannel(final SocketChannel socketChannel) throws Exception { final ChannelPipeline channelPipeline = socketChannel.pipeline(); boolean first = true; ChannelInboundHandler[] channelInboundHandlers = channelInboundHandlerFactory .createChannelInboundHandlers(); for (ChannelInboundHandler channelInboundHandler : channelInboundHandlers) { if (first) { channelPipeline.addFirst(channelInboundHandler); first = false; } else { channelPipeline.addLast(channelInboundHandler); } } channelPipeline.addLast("sourceOutputHandler", new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { byte[] data; if (msg.hasArray()) { data = msg.array(); } else { data = new byte[msg.readableBytes()]; msg.readBytes(data); } AbstractIntegrationMessageBuilder<byte[]> builder = getMessageBuilderFactory() .withPayload(data); sendMessage(builder.build()); } }); socketChannel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { socketChannel.close(); } }); } }); serverBootstrap.validate(); }
From source file:org.springframework.http.client.Netty4ClientHttpRequest.java
License:Apache License
@Override protected ListenableFuture<ClientHttpResponse> executeInternal(final HttpHeaders headers) throws IOException { final SettableListenableFuture<ClientHttpResponse> responseFuture = new SettableListenableFuture<ClientHttpResponse>(); ChannelFutureListener connectionListener = new ChannelFutureListener() { @Override//from w w w.jav a 2 s .c o m public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { Channel channel = future.channel(); channel.pipeline().addLast(new RequestExecuteHandler(responseFuture)); FullHttpRequest nettyRequest = createFullHttpRequest(headers); channel.writeAndFlush(nettyRequest); } else { responseFuture.setException(future.cause()); } } }; this.bootstrap.connect(this.uri.getHost(), getPort(this.uri)).addListener(connectionListener); return responseFuture; }
From source file:org.stem.client.Connection.java
License:Apache License
private ChannelFutureListener writeHandler(final Message.Request request, final ResponseHandler handler) { return new ChannelFutureListener() { @Override// www. j a va2s . co m public void operationComplete(ChannelFuture future) throws Exception { writeCounter.decrementAndGet(); if (!future.isSuccess()) { logger.debug("{} Error writing request {}", Connection.this, request); dispatcher.removeHandler(handler.streamId, true); ConnectionException e; if (future.cause() instanceof ClosedChannelException) { e = new ClientTransportException(address, "Error writing to closed channel"); } else { e = new ClientTransportException(address, "Error writing", future.cause()); } // No retries yet handler.callback.onException(Connection.this, defunct(e), System.nanoTime() - handler.startTime); } else { logger.trace("{} request sent successfully", Connection.this); } } }; }
From source file:org.thingsplode.synapse.endpoint.handlers.HttpRequestHandler.java
License:Apache License
private void upgradeToWebsocket(ChannelHandlerContext ctx, FullHttpRequest httpRequest) { String wsUrl = "ws://" + httpRequest.headers().get(HttpHeaderNames.HOST) + "/" + endpointId; //todo: configure frame size WebSocketServerHandshakerFactory wsHandshakeFactory = new WebSocketServerHandshakerFactory(wsUrl, null, false);//ww w . j a v a 2 s . c om WebSocketServerHandshaker handshaker = wsHandshakeFactory.newHandshaker(httpRequest); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), httpRequest) .addListener((ChannelFutureListener) new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { logger.debug("Switching to websocket. Replacing the " + Endpoint.HTTP_RESPONSE_HANDLER + " with " + Endpoint.WS_RESPONSE_HANDLER); ctx.pipeline().replace(Endpoint.HTTP_REQUEST_HANDLER, Endpoint.WS_REQUEST_HANDLER, new WebsocketRequestHandler(handshaker)); ctx.pipeline().replace(Endpoint.HTTP_RESPONSE_HANDLER, Endpoint.WS_RESPONSE_HANDLER, new WebsocketResponseHandler()); ctx.pipeline().addAfter(Endpoint.WS_RESPONSE_HANDLER, Endpoint.WS_COMMAND_HANDLER, new Command2WsEncoder()); if (ctx.pipeline().get(Endpoint.RESPONSE_INTROSPECTOR) != null) { ctx.pipeline().addAfter(Endpoint.RESPONSE_INTROSPECTOR, Endpoint.WS_REQUEST_INTROSPECTOR, new WebsocketIntrospector()); } } else { String msg = "Dispatching upgrade acknowledgement was not successfull due to "; if (future.cause() != null) { logger.error(msg + future.cause().getClass().getSimpleName() + " with message: " + future.cause().getMessage(), future.cause()); } else { logger.error(msg + " unknown reasons."); } } } }); } }
From source file:org.thingsplode.synapse.endpoint.handlers.WebsocketResponseHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Response response) throws Exception { byte[] content = serializationService.getSerializer(MediaType.APPLICATION_JSON).marshall(response); TextWebSocketFrame wsFrame = new TextWebSocketFrame(Unpooled.wrappedBuffer(content)); ChannelFuture cf = ctx.writeAndFlush(wsFrame) .addListener((ChannelFutureListener) new ChannelFutureListener() { @Override/* w ww . j a va 2 s .co m*/ public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { logger.error( "Closing channel due to an error while sending response to websocket client -> " + (future.cause() != null ? future.cause().getMessage() : "unknown reason.")); ctx.channel().close(); } } }); if (!response.getHeader().isKeepAlive()) { cf.addListener((ChannelFutureListener) (ChannelFuture future) -> { ctx.writeAndFlush(new CloseWebSocketFrame(true, 0)); }).addListener(ChannelFutureListener.CLOSE); } }