@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channel = ctx.channel(); channels.add(channel); attempts = 0; ctx.fireChannelActive(); }
private void callAfterAdd(ChannelHandlerContext ctx) { try { ctx.handler().afterAdd(ctx); } catch (Throwable t) { boolean removed = false; try { remove((DefaultChannelHandlerContext) ctx, false); removed = true; } catch (Throwable t2) { if (logger.isWarnEnabled()) { logger.warn("Failed to remove a handler: " + ctx.name(), t2); } } if (removed) { throw new ChannelPipelineException( ctx.handler().getClass().getName() + ".afterAdd() has thrown an exception; removed.", t); } else { throw new ChannelPipelineException( ctx.handler().getClass().getName() + ".afterAdd() has thrown an exception; also failed to remove.", t); } } }
@Override public void exceptionCaught(ChannelHandlerContext context, Throwable cause) { LOG.error(cause.getMessage(), cause); if (context.channel().isOpen()) { context.channel().close(); } }
@Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { Session session = new Session(ctx.getChannel()); netHandler.onConnected(session); ctx.setAttachment(session); }
@Override public final boolean trySend(WebDataMessage message) { if (!message.isBinary()) ctx.writeAndFlush(new TextWebSocketFrame(message.getStringBody())); else ctx.writeAndFlush( new BinaryWebSocketFrame(Unpooled.wrappedBuffer(message.getByteBufferBody()))); return true; }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception { if (!(me.getMessage() instanceof HttpRequest)) { ctx.sendUpstream(me); return; } HttpRequest request = (HttpRequest) me.getMessage(); Object response; // Look up resource String path = request.getUri(); String host = request.getHeader("host"); log.debug("Received request for path:" + path); boolean showHtml = false; if (path.endsWith("?html")) { showHtml = true; path = path.replace("?html", ""); } for (String service : resources.keySet()) { log.debug("Available Service: " + service); } Model model = resources.get(path); if (model != null) { if (request.getMethod() == HttpMethod.GET) { if (showHtml) { String html = HtmlCreator.createModelPage(model, new URI(path), host); response = ChannelBuffers.wrappedBuffer(html.getBytes(Charset.forName("UTF-8"))); log.debug("Returned html page for resource: " + path); } else { response = new SelfDescription(model, new URI(request.getUri())); log.debug("Resource found: " + path); } } else { response = new DefaultHttpResponse( request.getProtocolVersion(), HttpResponseStatus.METHOD_NOT_ALLOWED); log.debug("Method not allowed: " + request.getMethod()); } } else { response = HttpResponseFactory.createHttpResponse( request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND); log.debug("Resource not found: " + path); } // Send response ChannelFuture future = Channels.write(ctx.getChannel(), response); future.addListener(ChannelFutureListener.CLOSE); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap bootstrap = new Bootstrap(); bootstrap .group(inboundChannel.eventLoop()) .channel(ctx.channel().getClass()) .handler( new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // Create a default pipeline implementation. ChannelPipeline pipeline = ch.pipeline(); // add logging if (logger.isDebugEnabled()) { pipeline.addLast("logger", new LoggingHandler(" -->")); } // add HTTPS proxy -> server support if (secure) { SSLEngine engine = SSLFactory.sslContext().createSSLEngine(); engine.setUseClientMode(true); pipeline.addLast("proxy -> server ssl", new SslHandler(engine)); } // add handler pipeline.addLast( new ProxyRelayHandler( inboundChannel, bufferedCapacity, new RequestInterceptor(), " -->")); } }) .option(ChannelOption.AUTO_READ, false); ChannelFuture channelFuture = bootstrap.connect(remoteSocketAddress); outboundChannel = channelFuture.channel(); channelFuture.addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channelBuffer.clear(); bufferedMode = bufferedCapacity > 0; flushedBuffer = false; // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }
@Override public ChannelHandler get(String name) { ChannelHandlerContext ctx = context(name); if (ctx == null) { return null; } else { return ctx.handler(); } }
@Override protected final void die(Throwable cause) { super.die(cause); if (ctx.channel().isOpen()) ctx.close(); // Ensure to release server references userActor = null; ctx = null; }
/** Invoked when a connection is closed */ @Override public final void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) { GameSession session = (GameSession) ctx.getAttachment(); if (session != null) { synchronized (LogicService.getWorkerThread()) { World.getSingleton().unregisterPlayer(session.getPlayer()); } } ctx.getChannel().close(); }
private static void callBeforeRemove(ChannelHandlerContext ctx) { try { ctx.handler().beforeRemove(ctx); } catch (Throwable t) { throw new ChannelPipelineException( ctx.handler().getClass().getName() + ".beforeRemove() has thrown an exception; not removing.", t); } }
/** Invoked when an exception was raised by an I/O thread or a {@link ChannelHandler}. */ public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (this == ctx.getPipeline().getLast()) { logger.warn( "EXCEPTION, please implement " + getClass().getName() + ".exceptionCaught() for proper handling.", e.getCause()); } ctx.sendUpstream(e); }
@SuppressWarnings("unchecked") @Override public <T extends ChannelHandler> T get(Class<T> handlerType) { ChannelHandlerContext ctx = context(handlerType); if (ctx == null) { return null; } else { return (T) ctx.handler(); } }
private int outboundBufSize() { final int bufSize; final ChannelHandlerContext ctx = directOutboundContext(); if (ctx.hasOutboundByteBuffer()) { bufSize = ctx.outboundByteBuffer().readableBytes(); } else { bufSize = ctx.outboundMessageBuffer().size(); } return bufSize; }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelBuffer buffer = (ChannelBuffer) e.getMessage(); Route route = app.getRouter().parseRoute(getUtf(buffer)); byte[] data = new byte[buffer.readableBytes()]; buffer.readBytes(data); LocalSession localSession = sessions.getSession(ctx.getChannel().getId()).getLocalSession(); byte[] response = server.handle(route, localSession, data); if (response != null) { ctx.getChannel().write(response); } }
public void channelRead(final ChannelHandlerContext remoteChannelCtx, final Object msg) throws Exception { LoggerUtil.debug( logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Remote msg", msg); remainMsgCount++; if (remainMsgCount <= 5) { remoteChannelCtx.read(); } HttpObject ho = (HttpObject) msg; if (ho instanceof HttpResponse) { HttpResponse httpResponse = (HttpResponse) ho; LoggerUtil.info( forwardRestLogger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), httpResponse.getStatus(), httpResponse.getProtocolVersion()); httpResponse.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); httpResponse.headers().set("Proxy-Connection", HttpHeaders.Values.KEEP_ALIVE); } if (uaChannel.isActive()) { uaChannel .writeAndFlush(ho) .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { LoggerUtil.debug( logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Write to UA finished: " + future.isSuccess()); if (future.isSuccess()) { remainMsgCount--; remoteChannelCtx.read(); LoggerUtil.debug( logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Fire read again"); } else { remoteChannelCtx.close(); } } }); } else { remoteChannelCtx.close(); } }
protected void decode(ChannelHandlerContext context, ByteBuf buffer) throws Exception { ChannelPipeline pipeline = context.pipeline(); if (detectSsl && SslHandler.isEncrypted(buffer)) { SSLEngine engine = SSL_SERVER_CONTEXT.getValue().createSSLEngine(); engine.setUseClientMode(false); pipeline.addLast( new SslHandler(engine), new ChunkedWriteHandler(), new PortUnificationServerHandler(delegatingHttpRequestHandler, false, detectGzip)); } else { int magic1 = buffer.getUnsignedByte(buffer.readerIndex()); int magic2 = buffer.getUnsignedByte(buffer.readerIndex() + 1); if (detectGzip && magic1 == 31 && magic2 == 139) { pipeline.addLast( new JZlibEncoder(ZlibWrapper.GZIP), new JdkZlibDecoder(ZlibWrapper.GZIP), new PortUnificationServerHandler(delegatingHttpRequestHandler, detectSsl, false)); } else if (isHttp(magic1, magic2)) { NettyUtil.initHttpHandlers(pipeline); pipeline.addLast(delegatingHttpRequestHandler); if (BuiltInServer.LOG.isDebugEnabled()) { pipeline.addLast( new ChannelOutboundHandlerAdapter() { @Override public void write( ChannelHandlerContext context, Object message, ChannelPromise promise) throws Exception { if (message instanceof HttpResponse) { // BuiltInServer.LOG.debug("OUT HTTP:\n" + message); HttpResponse response = (HttpResponse) message; BuiltInServer.LOG.debug( "OUT HTTP: " + response.getStatus().code() + " " + response.headers().get("Content-type")); } super.write(context, message, promise); } }); } } else if (magic1 == 'C' && magic2 == 'H') { buffer.skipBytes(2); pipeline.addLast(new CustomHandlerDelegator()); } else { BuiltInServer.LOG.warn("unknown request, first two bytes " + magic1 + " " + magic2); context.close(); } } // must be after new channels handlers addition (netty bug?) ensureThatExceptionHandlerIsLast(pipeline); pipeline.remove(this); context.fireChannelRead(buffer); }
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleState e = ((IdleStateEvent) evt).state(); if (e == IdleState.ALL_IDLE) { // fire a channelInactive to trigger publish of Will ctx.fireChannelInactive(); ctx.close(); } /*else if (e.getState() == IdleState.WRITER_IDLE) { ctx.writeAndFlush(new PingMessage()); }*/ } }
@Override public final void flushNow() { if (inFlushNow || flushTaskInProgress != null) { return; } inFlushNow = true; ChannelHandlerContext ctx = directOutboundContext(); Throwable cause = null; try { if (ctx.hasOutboundByteBuffer()) { ByteBuf out = ctx.outboundByteBuffer(); int oldSize = out.readableBytes(); try { doFlushByteBuffer(out); } catch (Throwable t) { cause = t; } finally { final int newSize = out.readableBytes(); final int writtenBytes = oldSize - newSize; if (writtenBytes > 0) { flushFutureNotifier.increaseWriteCounter(writtenBytes); if (newSize == 0) { out.discardReadBytes(); } } } } else { MessageBuf<Object> out = ctx.outboundMessageBuffer(); int oldSize = out.size(); try { doFlushMessageBuffer(out); } catch (Throwable t) { cause = t; } finally { flushFutureNotifier.increaseWriteCounter(oldSize - out.size()); } } if (cause == null) { flushFutureNotifier.notifyFlushFutures(); } else { flushFutureNotifier.notifyFlushFutures(cause); if (cause instanceof IOException) { close(voidFuture()); } } } finally { inFlushNow = false; } }
/** * {@inheritDoc} Down-casts the received upstream event into more meaningful sub-type event and * calls an appropriate handler method with the down-casted event. */ public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof MessageEvent) { messageReceived(ctx, (MessageEvent) e); } else if (e instanceof WriteCompletionEvent) { WriteCompletionEvent evt = (WriteCompletionEvent) e; writeComplete(ctx, evt); } else if (e instanceof ChildChannelStateEvent) { ChildChannelStateEvent evt = (ChildChannelStateEvent) e; if (evt.getChildChannel().isOpen()) { childChannelOpen(ctx, evt); } else { childChannelClosed(ctx, evt); } } else if (e instanceof ChannelStateEvent) { ChannelStateEvent evt = (ChannelStateEvent) e; switch (evt.getState()) { case OPEN: if (Boolean.TRUE.equals(evt.getValue())) { channelOpen(ctx, evt); } else { channelClosed(ctx, evt); } break; case BOUND: if (evt.getValue() != null) { channelBound(ctx, evt); } else { channelUnbound(ctx, evt); } break; case CONNECTED: if (evt.getValue() != null) { channelConnected(ctx, evt); } else { channelDisconnected(ctx, evt); } break; case INTEREST_OPS: channelInterestChanged(ctx, evt); break; default: ctx.sendUpstream(e); } } else if (e instanceof ExceptionEvent) { exceptionCaught(ctx, (ExceptionEvent) e); } else { ctx.sendUpstream(e); } }
@Override protected void doMessageReceived(ClientConnection conn, ChannelHandlerContext ctx, Object msg) { if (conn == null || conn.isClosed()) { return; } boolean valid = false; if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; conn.handleResponse(response); valid = true; } if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; if (chunk.content().isReadable()) { Buffer buff = new Buffer(chunk.content().slice()); conn.handleResponseChunk(buff); } if (chunk instanceof LastHttpContent) { conn.handleResponseEnd((LastHttpContent) chunk); } valid = true; } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; switch (frame.getType()) { case BINARY: case TEXT: conn.handleWsFrame(frame); break; case PING: // Echo back the content of the PING frame as PONG frame as specified in RFC 6455 // Section 5.5.2 ctx.writeAndFlush( new DefaultWebSocketFrame(WebSocketFrame.FrameType.PONG, frame.getBinaryData())); break; case CLOSE: if (!closeFrameSent) { // Echo back close frame and close the connection once it was written. // This is specified in the WebSockets RFC 6455 Section 5.4.1 ctx.writeAndFlush(frame).addListener(ChannelFutureListener.CLOSE); closeFrameSent = true; } break; } valid = true; } if (!valid) { throw new IllegalStateException("Invalid object " + msg); } }
/** Invoked when a packet is received */ @Override public final void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { GameSession session = (GameSession) ctx.getAttachment(); if (e.getMessage() instanceof Message) { if (session != null) { synchronized (LogicService.getWorkerThread()) { Message packet = (Message) e.getMessage(); session.pushPacket(packet); } } } if (e.getMessage() instanceof ChannelBuffer) { ctx.getChannel().write(ctx); } }
@Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { Channel channel = ctx.getChannel(); if (!sessions.removeSession(channel.getId())) { Log.error("删除Session失败! sockId: " + channel.getId()); } }
@Override public void execute() throws Exception { if (!ctx.getChannel().isConnected()) { try { ctx.getChannel().close(); } catch (Throwable e) { // Ignore } return; } // Check the exceeded size before re rendering so we can render the error if the size is // exceeded saveExceededSizeError(nettyRequest, request, response); ActionInvoker.invoke(request, response); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { // На канале произошло исключение. Выводим ошибку, закрываем канал. // Server.logger.log(Level.WARNING, "Exception from downstream", e.getCause()); ctx.getChannel().close(); log.info("exceptionCaught", e.getCause()); }
protected static void writeResponse( ChannelHandlerContext ctx, Response response, HttpResponse nettyResponse, HttpRequest nettyRequest) { Logger.trace("writeResponse: begin"); byte[] content = null; final boolean keepAlive = isKeepAlive(nettyRequest); if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) { content = new byte[0]; } else { content = response.out.toByteArray(); } ChannelBuffer buf = ChannelBuffers.copiedBuffer(content); nettyResponse.setContent(buf); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. Logger.trace("writeResponse: content length [" + response.out.size() + "]"); setContentLength(nettyResponse, response.out.size()); } ChannelFuture f = ctx.getChannel().write(nettyResponse); // Decide whether to close the connection or not. if (!keepAlive) { // Close the connection when the whole content is written out. f.addListener(ChannelFutureListener.CLOSE); } Logger.trace("writeResponse: end"); }
@Override public void exceptionCaught(ChannelHandlerContext remoteChannelCtx, Throwable cause) throws Exception { logger.error( cause.getMessage() + uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), cause); remoteChannelCtx.close(); }
public static void serve404( NotFound e, ChannelHandlerContext ctx, Request request, HttpRequest nettyRequest) { Logger.trace("serve404: begin"); HttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); nettyResponse.setHeader(SERVER, signature); nettyResponse.setHeader(CONTENT_TYPE, "text/html"); Map<String, Object> binding = getBindingForErrors(e, false); String format = Request.current().format; if (format == null) { format = "txt"; } nettyResponse.setHeader( CONTENT_TYPE, (MimeTypes.getContentType("404." + format, "text/plain"))); String errorHtml = TemplateLoader.load("errors/404." + format).render(binding); try { ChannelBuffer buf = ChannelBuffers.copiedBuffer(errorHtml.getBytes("utf-8")); nettyResponse.setContent(buf); ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse); writeFuture.addListener(ChannelFutureListener.CLOSE); } catch (UnsupportedEncodingException fex) { Logger.error(fex, "(utf-8 ?)"); } Logger.trace("serve404: end"); }
@Override public void channelActive(@NotNull ChannelHandlerContext ctx) { startTime = System.nanoTime(); ctx.writeAndFlush(firstMessage); System.out.print("Running throughput test ( for 10 seconds ) "); }
@Override public synchronized void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = ctx.getChannel(); List<Command<K, V, ?>> tmp = new ArrayList<Command<K, V, ?>>(queue.size() + 2); if (password != null) { CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(password); tmp.add(new Command<K, V, String>(AUTH, new StatusOutput<K, V>(codec), args, false)); } if (db != 0) { CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(db); tmp.add(new Command<K, V, String>(SELECT, new StatusOutput<K, V>(codec), args, false)); } tmp.addAll(queue); queue.clear(); for (Command<K, V, ?> cmd : tmp) { if (!cmd.isCancelled()) { queue.add(cmd); channel.write(cmd); } } tmp.clear(); }