@Override public void flush(ChannelHandlerContext ctx) throws Exception { // Do not encrypt the first write request if this handler is // created with startTLS flag turned on. if (startTls && !sentFirstMessage) { sentFirstMessage = true; for (; ; ) { PendingWrite pendingWrite = pendingUnencryptedWrites.poll(); if (pendingWrite == null) { break; } ctx.write(pendingWrite.msg(), (ChannelPromise) pendingWrite.recycleAndGet()); } ctx.flush(); return; } if (pendingUnencryptedWrites.isEmpty()) { pendingUnencryptedWrites.add(PendingWrite.newInstance(Unpooled.EMPTY_BUFFER, null)); } if (!handshakePromise.isDone()) { flushedBeforeHandshakeDone = true; } wrap(ctx, false); ctx.flush(); }
@Override public void channelWritabilityChanged(final ChannelHandlerContext ctx) throws Exception { if (!ctx.channel().isWritable()) { ctx.flush(); } ctx.fireChannelWritabilityChanged(); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Send greeting for a new connection. ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n"); ctx.write("It is " + new Date() + " now.\r\n"); ctx.flush(); }
private void protocolViolation(ChannelHandlerContext ctx, String reason) { checkpoint(State.CORRUPT); if (ctx.channel().isActive()) { ctx.flush().addListener(ChannelFutureListener.CLOSE); } throw new CorruptedFrameException(reason); }
private void flush0( final ChannelHandlerContext ctx, final int bytesConsumed, final Throwable cause) { ChannelFuture flushFuture = ctx.flush( ctx.newFuture() .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (ctx.executor() == ctx.channel().eventLoop()) { notifyFlushFutures(bytesConsumed, cause, future); } else { synchronized (flushFutureNotifier) { notifyFlushFutures(bytesConsumed, cause, future); } } } private void notifyFlushFutures( int bytesConsumed, Throwable cause, ChannelFuture future) { flushFutureNotifier.increaseWriteCounter(bytesConsumed); if (future.isSuccess()) { flushFutureNotifier.notifyFlushFutures(cause); } else { flushFutureNotifier.notifyFlushFutures(cause, future.cause()); } } })); safeClose(ctx, flushFuture, ctx.newFuture()); }
/** * 发送消息 * * @param m */ public void send(Msg m) { if (chtx != null && chtx.channel().isOpen()) { logger.info("client发送消息:" + m); chtx.write(m); chtx.flush(); } }
@Override public void flush() throws IOException { if (buf.isReadable()) { writeToChannel(); } chc.flush(); }
@Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { log.info("ECHO active " + NioUdtProvider.socketUDT(ctx.channel()).toStringOptions()); final MessageBuf<Object> out = ctx.nextOutboundMessageBuffer(); out.add(message); ctx.flush(); }
protected void doOnTerminate( ChannelHandlerContext ctx, ChannelFuture last, final ChannelPromise promise, final Throwable exception) { if (ctx.channel().isOpen()) { ChannelFutureListener listener = future -> { if (exception != null) { promise.tryFailure(exception); } else if (future.isSuccess()) { promise.trySuccess(); } else { promise.tryFailure(future.cause()); } }; if (last != null) { ctx.flush(); last.addListener(listener); } else { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(listener); } } else { if (exception != null) { promise.tryFailure(exception); } else { promise.trySuccess(); } } }
@Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { if (needsFlush) { needsFlush = false; ctx.flush(); } super.channelReadComplete(ctx); }
@Override public void flush(ChannelHandlerContext ctx, ChannelFuture future) throws Exception { ByteBuf buf = ctx.outboundByteBuffer(); if (logger.isEnabled(internalLevel)) { logger.log(internalLevel, format(ctx, formatBuffer("WRITE", buf))); } ctx.nextOutboundByteBuffer().writeBytes(buf); ctx.flush(future); }
@Override protected void messageReceived(final ChannelHandlerContext ctx, final UdtMessage message) throws Exception { final ByteBuf byteBuf = message.data(); meter.mark(byteBuf.readableBytes()); final MessageBuf<Object> out = ctx.nextOutboundMessageBuffer(); out.add(message); ctx.flush(); }
@Override protected void decode(final ChannelHandlerContext ctx, ByteBuf byteIn, List<Object> out) throws Exception { connection.inputBuffer(byteIn); ctx.flush(); // if (connection.capacity() > 0) // { // ctx.read(); // } }
@Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { try { ctx.flush(); } finally { if (!autoRead) { ctx.read(); } } }
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { FullHttpRequest request = this.request = msg; QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); uriRequest = queryStringDecoder.path(); logger.debug("Msg: " + uriRequest); if (uriRequest.contains("gre/") || uriRequest.contains("img/") || uriRequest.contains("res/") || uriRequest.contains("favicon.ico")) { HttpWriteCacheEnable.writeFile( request, ctx, Configuration.configuration.getHttpBasePath() + uriRequest, R66SESSION + Configuration.configuration.getHOST_ID()); ctx.flush(); return; } checkSession(ctx.channel()); if (!authentHttp.isAuthenticated()) { logger.debug("Not Authent: " + uriRequest + ":{}", authentHttp); checkAuthent(ctx); return; } String find = uriRequest; if (uriRequest.charAt(0) == '/') { find = uriRequest.substring(1); } find = find.substring(0, find.indexOf(".")); REQUEST req = REQUEST.index; try { req = REQUEST.valueOf(find); } catch (IllegalArgumentException e1) { req = REQUEST.index; logger.debug("NotFound: " + find + ":" + uriRequest); } switch (req) { case index: responseContent.append(index()); break; case Logon: responseContent.append(index()); break; case System: responseContent.append(System()); break; default: responseContent.append(index()); break; } writeResponse(ctx); }
private void sendNumbers() { // Do not send more than 4096 numbers. ChannelFuture future = null; for (int i = 0; i < 4096 && next <= FactorialClient.COUNT; i++) { future = ctx.write(Integer.valueOf(next)); next++; } if (next <= FactorialClient.COUNT) { assert future != null; future.addListener(numberSender); } ctx.flush(); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); System.out.println("active..."); ctx.write(new MsgTest()); ctx.flush(); // ctx.write(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8)); // ctx.write("abcd"); // ctx.flush(); // ctx.channel().write("abcd"); // ctx.channel().flush(); }
@Override protected void encode(ChannelHandlerContext ctx, NetBuffer buf, ByteBuf out) throws Exception { out = ctx.alloc().directBuffer(); byte[] data = buf.getMessages(); int dataLength = data.length; logger.debug("=====length:[\t" + dataLength + "\t]======="); // д��Ϣ out.writeShort(NetConstants.MAGIC_HEADER); // Matgic Header out.writeInt(dataLength); // ��Ҫ����ָ���� out.writeBytes(data); // ����protobuf���� ctx.write(out); ctx.flush(); }
/** * Remove all references to the channel. 1) the map of a channel (socket) to its interests. 2) the * map of interests to its channels. * * <p>As each interest is removed inform all channels having a similar interest. * * @param sourceCtx */ public void unregister(final ChannelHandlerContext sourceCtx) { final SocketAddress key = sourceCtx.channel().remoteAddress(); majorLogger.info("unregister channel {}", key); final Interest.ChannelInterestSet channelInterestSet = this.channelInterestMap.remove(key); if (channelInterestSet == null) { majorLogger.warn( "nothing to unregister in interest map: {}", this.channelInterestMap.keySet()); return; } final String trackingGuid = UUID.randomUUID().toString(); majorLogger.warn("no interested channel set"); for (final Interest interest : channelInterestSet.getInterestList()) { if (!this.interestedChannelMap.containsKey(interest)) { continue; } final Interest.InterestedChannelSet interestedChannelSet = this.interestedChannelMap.get(interest); interestedChannelSet.removeItem(sourceCtx, interest); majorLogger.info("unregistered interest {}", interest); // this.interestedChannelMap.put(interest, interestedChannelSet); // an implicit DISINTEREST message will be sent to all interested channels final MetaLinkMsg.Edit.Builder editBuilder = MetaLinkMsg.Edit.newBuilder() .addMode(MetaLinkMsg.Edit.EditMode.DISINTEREST) .setEditMode(MetaLinkMsg.Edit.EditMode.DISINTEREST) .setGuid(trackingGuid) .setSequence(sequenceNumber.incrementAndGet()) .addAllTopic(interest.getTopic()) .addOrigin(sourceCtx.channel().remoteAddress().toString()) .addOrigin(METALINK_BRIDGE_NAME); final MetaLinkMsg.Edit disinterestMsg = editBuilder.build(); majorLogger.trace("expressing disinterest to all channels except source"); for (final Map.Entry<SocketAddress, Interest.ChannelInterestSet> entry : this.channelInterestMap.entrySet()) { final ChannelHandlerContext ctx = entry.getValue().context; if (isSameChannel(ctx, sourceCtx)) { continue; } majorLogger.trace("disinterest {} to {}", trackingGuid, ctx.channel().remoteAddress()); ctx.write(disinterestMsg); ctx.flush(); detailLogger.info("message sent:\n{}", disinterestMsg); } } }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { logger.info("StringEncoder response to client."); String serverMsg = (String) msg; FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(serverMsg.getBytes())); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); ctx.flush(); }
@Override public void flush(ChannelHandlerContext ctx) throws Exception { // Do not encrypt the first write request if this handler is // created with startTLS flag turned on. if (startTls && !sentFirstMessage) { sentFirstMessage = true; pendingUnencryptedWrites.removeAndWriteAll(); ctx.flush(); return; } if (pendingUnencryptedWrites.isEmpty()) { // It's important to NOT use a voidPromise here as the user // may want to add a ChannelFutureListener to the ChannelPromise later. // // See https://github.com/netty/netty/issues/3364 pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, ctx.newPromise()); } if (!handshakePromise.isDone()) { flushedBeforeHandshake = true; } wrap(ctx, false); ctx.flush(); }
/** Central handler for all exceptions caught during HTTP/2 processing. */ @Override public void onException(ChannelHandlerContext ctx, Throwable cause) { Http2Exception embedded = getEmbeddedHttp2Exception(cause); if (isStreamError(embedded)) { onStreamError(ctx, cause, (StreamException) embedded); } else if (embedded instanceof CompositeStreamException) { CompositeStreamException compositException = (CompositeStreamException) embedded; for (StreamException streamException : compositException) { onStreamError(ctx, cause, streamException); } } else { onConnectionError(ctx, cause, embedded); } ctx.flush(); }
@Override public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception { if (msg instanceof Frame) { final Frame sockJSFrame = (Frame) msg; if (sockJSFrame instanceof MessageFrame) { final MessageFrame messageFrame = (MessageFrame) sockJSFrame; final List<String> messages = messageFrame.messages(); for (String message : messages) { ctx.write(new TextWebSocketFrame(message)); } } } ctx.flush(); promise.setSuccess(); }
@Override public void flush(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { ByteBuf in = ctx.outboundByteBuffer(); try { MessageBuf<Object> out = ctx.nextOutboundMessageBuffer(); ByteBuf payload = Unpooled.buffer(in.readableBytes()); payload.writeBytes(in); out.add(new SctpMessage(streamIdentifier, protocolIdentifier, payload)); in.discardReadBytes(); } catch (Throwable t) { ctx.fireExceptionCaught(new EncoderException(t)); } ctx.flush(promise); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2) ByteBuf in = (ByteBuf) msg; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (in.isReadable()) { // (1) byte readByte = in.readByte(); baos.write(readByte); // System.out.flush(); ctx.flush(); } System.out.println("Msg Read: " + baos.toString()); } finally { // System.out.println("finish!"); ReferenceCountUtil.release(msg); // (2) } }
@Override public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { // Avoid NotYetConnectedException if (!ctx.channel().isActive()) { ctx.close(promise); return; } ChannelFuture future = goAway(ctx, null); ctx.flush(); // If there are no active streams, close immediately after the send is complete. // Otherwise wait until all streams are inactive. if (isGracefulShutdownComplete()) { future.addListener(new ClosingChannelFutureListener(ctx, promise)); } else { closeListener = new ClosingChannelFutureListener(ctx, promise); } }
@Override public void onNext(Object w) { if (w == null) { throw Exceptions.argumentIsNullException(); } if (subscription == null) { throw Exceptions.failWithCancel(); } try { ChannelFuture cf = doOnWrite(w, ctx); if (cf != null) { cf.addListener(writeListener); } ctx.flush(); } catch (Throwable t) { log.error("Write error for " + w, t); onError(t); throw Exceptions.failWithCancel(); } }
@Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // Discard bytes of the cumulation buffer if needed. discardSomeReadBytes(); if (needsFlush) { needsFlush = false; ctx.flush(); } // If handshake is not finished yet, we need more data. if (!ctx.channel().config().isAutoRead() && (!firedChannelRead || !handshakePromise.isDone())) { // No auto-read used and no message passed through the ChannelPipeline or the handhshake was // not complete // yet, which means we need to trigger the read to ensure we not encounter any stalls. ctx.read(); } firedChannelRead = false; ctx.fireChannelReadComplete(); }
private Future<Channel> handshake() { final ScheduledFuture<?> timeoutFuture; if (handshakeTimeoutMillis > 0) { timeoutFuture = ctx.executor() .schedule( new Runnable() { @Override public void run() { if (handshakePromise.isDone()) { return; } notifyHandshakeFailure(HANDSHAKE_TIMED_OUT); } }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS); } else { timeoutFuture = null; } handshakePromise.addListener( new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> f) throws Exception { if (timeoutFuture != null) { timeoutFuture.cancel(false); } } }); try { engine.beginHandshake(); wrapNonAppData(ctx, false); ctx.flush(); } catch (Exception e) { notifyHandshakeFailure(e); } return handshakePromise; }
@Override public void encode(ChannelHandlerContext ctx, Packet<PacketListener> packet, ByteBuf output) throws Exception { Channel channel = ctx.channel(); EnumProtocol currentProtocol = channel.attr(currentStateAttrKey).get(); final Integer packetId = currentProtocol.a(direction, packet); if (packetId == null) { throw new IOException("Can't serialize unregistered packet"); } ClientBoundMiddlePacket<RecyclableCollection<PacketData>> packetTransformer = dataRemapperRegistry.getTransformer(currentProtocol, packetId); if (packetTransformer != null) { serverdata.clear(); packet.b(serverdata); if (packetTransformer.needsPlayer()) { packetTransformer.setPlayer(ChannelUtils.getBukkitPlayer(channel)); } packetTransformer.readFromServerData(serverdata); packetTransformer.setLocalStorage(storage); packetTransformer.handle(); RecyclableCollection<PacketData> data = packetTransformer.toData(version); try { for (PacketData packetdata : data) { ByteBuf senddata = Allocator.allocateBuffer(); senddata.writeByte( packetIdRegistry.getNewPacketId(currentProtocol, packetdata.getPacketId())); senddata.writeBytes(packetdata); ctx.write(senddata); } ctx.flush(); } finally { for (PacketData packetdata : data) { packetdata.recycle(); } data.recycle(); } } }