io.netty.channel.Channel#flush ( )源码实例Demo

下面列出了io.netty.channel.Channel#flush ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hasor   文件: TelNettyHandler.java
private void printWelcome(Channel channel) {
    if (TelUtils.aBoolean(this.telSession, SILENT)) {
        logger.info("tConsole -> silent, ignore Welcome info.");
        return;
    }
    logger.info("tConsole -> send Welcome info.");
    // Send greeting for a new connection.
    channel.write("--------------------------------------------\r\n\r\n");
    channel.write("Welcome to tConsole!\r\n");
    channel.write("\r\n");
    channel.write("     login : " + new Date() + " now. form " + channel.remoteAddress() + "\r\n");
    channel.write("    workAt : " + channel.localAddress() + "\r\n");
    channel.write("Tips: You can enter a 'help' or 'help -a' for more information.\r\n");
    channel.write("use the 'exit' or 'quit' out of the console.\r\n");
    channel.write("--------------------------------------------\r\n");
    channel.write(CMD);
    channel.flush();
}
 
源代码2 项目: pravega   文件: ClientConnectionImpl.java
@Override
public void sendAsync(List<Append> appends, CompletedCallback callback) {
    Channel ch;
    try {
        checkClientConnectionClosed();
        ch = nettyHandler.getChannel();
    } catch (ConnectionFailedException e) {
        callback.complete(new ConnectionFailedException("Connection to " + connectionName + " is not established."));
        return;
    }
    PromiseCombiner combiner = new PromiseCombiner(ImmediateEventExecutor.INSTANCE);
    for (Append append : appends) {
        combiner.add(ch.write(append));
    }
    ch.flush();
    ChannelPromise promise = ch.newPromise();
    promise.addListener(future -> {
        nettyHandler.setRecentMessage();
        Throwable cause = future.cause();
        callback.complete(cause == null ? null : new ConnectionFailedException(cause));
    });
    combiner.finish(promise);
}
 
@ServiceActivator(inputChannel = Sink.INPUT)
public void websocketSink(Message<?> message) {
	if (logger.isTraceEnabled()) {
		logger.trace(String.format("Handling message: %s", message));
	}

	SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
	headers.setMessageTypeIfNotSet(SimpMessageType.MESSAGE);
	String messagePayload = message.getPayload().toString();
	for (Channel channel : WebsocketSinkServer.channels) {
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Writing message %s to channel %s", messagePayload, channel.localAddress()));
		}

		channel.write(new TextWebSocketFrame(messagePayload));
		channel.flush();
	}

	if (traceEndpointEnabled) {
		addMessageToTraceRepository(message);
	}
}
 
源代码4 项目: consulo   文件: Responses.java
static void send(HttpResponse response, Channel channel, boolean close) {
  if (!channel.isActive()) {
    return;
  }

  ChannelFuture future = channel.write(response);
  if (!(response instanceof FullHttpResponse)) {
    channel.write(LastHttpContent.EMPTY_LAST_CONTENT);
  }
  channel.flush();
  if (close) {
    future.addListener(ChannelFutureListener.CLOSE);
  }
}
 
源代码5 项目: blynk-server   文件: HardwareLoginHandler.java
private void completeLogin(Channel channel, Session session, User user,
                                  DashBoard dash, Device device, int msgId) {
    log.debug("completeLogin. {}", channel);

    session.addHardChannel(channel);
    channel.write(ok(msgId));

    String body = dash.buildPMMessage(device.id);
    if (dash.isActive && body != null) {
        channel.write(makeASCIIStringMessage(HARDWARE, HARDWARE_PIN_MODE_MSG_ID, body));
    }

    channel.flush();

    String responseBody = String.valueOf(dash.id) + DEVICE_SEPARATOR + device.id;
    session.sendToApps(HARDWARE_CONNECTED, msgId, dash.id, responseBody);
    log.trace("Connected device id {}, dash id {}", device.id, dash.id);
    device.connected();
    if (device.firstConnectTime == 0) {
        device.firstConnectTime = device.connectTime;
    }
    if (allowStoreIp) {
        device.lastLoggedIP = IPUtils.getIp(channel.remoteAddress());
    }

    log.info("{} hardware joined.", user.email);
}
 
源代码6 项目: opc-ua-stack   文件: UaTcpStackServer.java
public void secureChannelIssuedOrRenewed(ServerSecureChannel secureChannel, long lifetimeMillis) {
    long channelId = secureChannel.getChannelId();

    /*
     * Cancel any existing timeouts and start a new one.
     */
    Timeout timeout = timeouts.remove(channelId);
    boolean cancelled = (timeout == null || timeout.cancel());

    if (cancelled) {
        timeout = wheelTimer.newTimeout(t ->
                closeSecureChannel(secureChannel), lifetimeMillis, TimeUnit.MILLISECONDS);

        timeouts.put(channelId, timeout);

        /*
         * If this is a reconnect there might be responses queued, so drain those.
         */
        Channel channel = secureChannel.attr(BoundChannelKey).get();

        if (channel != null) {
            List<ServiceResponse> responses = responseQueues.removeAll(channelId);

            responses.forEach(channel::write);
            channel.flush();
        }
    }
}
 
源代码7 项目: netty-4.1.22   文件: DefaultChannelGroup.java
@Override
public ChannelGroup flush(ChannelMatcher matcher) {
    for (Channel c: nonServerChannels.values()) {
        if (matcher.matches(c)) {
            c.flush();
        }
    }
    return this;
}
 
源代码8 项目: sofa-rpc   文件: AbstractHttp2ClientTransport.java
protected int sendHttpRequest(FullHttpRequest httpRequest, AbstractHttpClientHandler callback) {
    final int requestId = streamId.getAndAdd(2);
    Channel channel = this.channel.channel();
    responseChannelHandler.put(requestId, channel.write(httpRequest), callback);
    channel.flush();
    return requestId;
}
 
源代码9 项目: tchannel-java   文件: ResponseRouter.java
protected void sendRequest() {

        if (!busy.compareAndSet(false, true)) {
            return;
        }

        Channel channel = ctx.channel();
        try {
            boolean flush = false;
            while (!requestQueue.isEmpty() && channel.isWritable()) {
                long id = requestQueue.poll();
                OutRequest<?> outRequest = requestMap.get(id);
                if (outRequest != null) {
                    outRequest.setChannelFuture(channel.write(outRequest.getRequest()));
                    flush = true;
                }
            }

            if (flush) {
                channel.flush();
            }
        } finally {
            busy.set(false);
        }

        // in case there are new request added
        if (channel.isWritable() && !requestQueue.isEmpty()) {
            sendRequest();
        }
    }
 
源代码10 项目: zuul   文件: ProxyEndpoint.java
private void writeClientRequestToOrigin(final PooledConnection conn, int readTimeout) {
    final Channel ch = conn.getChannel();
    passport.setOnChannel(ch);

    // set read timeout on origin channel
    ch.attr(ClientTimeoutHandler.ORIGIN_RESPONSE_READ_TIMEOUT).set(readTimeout);

    context.set(ORIGIN_CHANNEL, ch);
    context.set(POOLED_ORIGIN_CONNECTION_KEY, conn);

    preWriteToOrigin(chosenServer.get(), zuulRequest);

    final ChannelPipeline pipeline = ch.pipeline();
    originResponseReceiver = getOriginResponseReceiver();
    pipeline.addBefore("connectionPoolHandler", OriginResponseReceiver.CHANNEL_HANDLER_NAME, originResponseReceiver);

    // check if body needs to be repopulated for retry
    repopulateRetryBody();

    ch.write(zuulRequest);
    writeBufferedBodyContent(zuulRequest, ch);
    ch.flush();

    //Get ready to read origin's response
    ch.read();

    originConn = conn;
    channelCtx.read();
}
 
源代码11 项目: blynk-server   文件: ReadingWidgetsWorker.java
private void process(long now) {
    for (Map.Entry<UserKey, Session> entry : sessionDao.userSession.entrySet()) {
        Session session = entry.getValue();
        //for now checking widgets for active app only
        if ((allowRunWithoutApp || session.isAppConnected()) && session.isHardwareConnected()) {
            UserKey userKey = entry.getKey();
            User user = userDao.users.get(userKey);
            if (user != null) {
                Profile profile = user.profile;
                for (DashBoard dashBoard : profile.dashBoards) {
                    if (dashBoard.isActive) {
                        for (Channel channel : session.hardwareChannels) {
                            HardwareStateHolder stateHolder = StateHolderUtil.getHardState(channel);
                            if (stateHolder != null && stateHolder.dash.id == dashBoard.id) {
                                int deviceId = stateHolder.device.id;
                                for (Widget widget : dashBoard.widgets) {
                                    if (widget instanceof FrequencyWidget) {
                                        process(channel, (FrequencyWidget) widget,
                                                profile, dashBoard, deviceId, now);
                                    } else if (widget instanceof DeviceTiles) {
                                        processDeviceTile(channel, (DeviceTiles) widget, deviceId, now);
                                    }
                                }
                                channel.flush();
                            }
                        }
                    }
                }
            }
        }
    }
}
 
private void closeChannelAndEventLoop(Channel c) {
	c.flush();
	c.deregister();
	c.close();
	c.eventLoop().shutdownGracefully();
}
 
源代码13 项目: netty-4.1.22   文件: HttpUploadClient.java
/**
 * Multipart example
 */
private static void formpostmultipart(
        Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory,
        Iterable<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception {
    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder =
            new HttpPostRequestEncoder(factory, request, true); // true => multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute from previous request in formpost()
    bodyRequestEncoder.setBodyHttpDatas(bodylist);

    // finalize request
    bodyRequestEncoder.finalizeRequest();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}
 
源代码14 项目: zuul   文件: ClientResponseWriter.java
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    final Channel channel = ctx.channel();

    if (msg instanceof HttpResponseMessage) {
        final HttpResponseMessage resp = (HttpResponseMessage) msg;

        if (skipProcessing(resp)) {
            return;
        }

        if ((! isHandlingRequest) || (startedSendingResponseToClient)) {
            /* This can happen if we are already in the process of streaming response back to client OR NOT within active
               request/response cycle and something like IDLE or Request Read timeout occurs. In that case we have no way
               to recover other than closing the socket and cleaning up resources used by BOTH responses.
             */
            resp.disposeBufferedBody();
            if (zuulResponse != null) zuulResponse.disposeBufferedBody();
            ctx.close(); //This will trigger CompleteEvent if one is needed
            return;
        }

        startedSendingResponseToClient = true;
        zuulResponse = resp;
        if ("close".equalsIgnoreCase(zuulResponse.getHeaders().getFirst("Connection"))) {
            closeConnection = true;
        }
        channel.attr(ATTR_ZUUL_RESP).set(zuulResponse);

        if (channel.isActive()) {

            // Track if this is happening.
            if (! ClientRequestReceiver.isLastContentReceivedForChannel(channel)) {

                StatusCategory status = StatusCategoryUtils.getStatusCategory(ClientRequestReceiver.getRequestFromChannel(channel));
                if (ZuulStatusCategory.FAILURE_CLIENT_TIMEOUT.equals(status)) {
                    // If the request timed-out while being read, then there won't have been any LastContent, but thats ok because the connection will have to be discarded anyway.
                }
                else {
                    responseBeforeReceivedLastContentCounter.increment();
                    LOG.warn("Writing response to client channel before have received the LastContent of request! "
                            + zuulResponse.getInboundRequest().getInfoForLogging() + ", "
                            + ChannelUtils.channelInfoForLogging(channel));
                }
            }

            // Write out and flush the response to the client channel.
            channel.write(buildHttpResponse(zuulResponse));
            writeBufferedBodyContent(zuulResponse, channel);
            channel.flush();
        } else {
            channel.close();
        }
    }
    else if (msg instanceof HttpContent) {
        final HttpContent chunk = (HttpContent) msg;
        if (channel.isActive()) {
            channel.writeAndFlush(chunk);
        } else {
            chunk.release();
            channel.close();
        }
    }
    else {
        //should never happen
        ReferenceCountUtil.release(msg);
        throw new ZuulException("Received invalid message from origin", true);
    }
}
 
源代码15 项目: withme3.0   文件: MessageServiceImpl.java
private void sendMessage(Channel channel, String message) {
    channel.write(new TextWebSocketFrame(message));
    channel.flush();
}
 
private void closeChannelAndEventLoop(Channel c) {
	c.flush();
	c.deregister();
	c.close();
	c.eventLoop().shutdownGracefully();
}
 
源代码17 项目: azeroth   文件: RequestorSupport.java
@Override
public void request(Channel channel) {
    List<Object> requests = writeRequests(channel.alloc());
    requests.forEach(channel::write);
    channel.flush();
}
 
源代码18 项目: etherjar   文件: Subscription.java
public void start(Channel channel, ObjectMapper objectMapper, Integer requestId) throws JsonProcessingException {
    this.channel = channel;
    RequestJson<Integer> json = new RequestJson<>("eth_subscribe", params, requestId);
    channel.write(new TextWebSocketFrame(objectMapper.writeValueAsString(json)));
    channel.flush();
}
 
源代码19 项目: netty4.0.27Learn   文件: HttpUploadClient.java
/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 */
private static List<InterfaceHttpData> formpost(
        Bootstrap bootstrap,
        String host, int port, URI uriSimple, File file, HttpDataFactory factory,
        List<Entry<String, String>> headers) throws Exception {
    // XXX /formpost
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder =
            new HttpPostRequestEncoder(factory, request, false);  // false => not multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    bodyRequestEncoder.addBodyAttribute("getform", "POST");
    bodyRequestEncoder.addBodyAttribute("info", "first value");
    bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&");
    bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
    bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
    bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

    // finalize request
    request = bodyRequestEncoder.finalizeRequest();

    // Create the bodylist to be reused on the last version with Multipart support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Do not clear here since we will reuse the InterfaceHttpData on the next request
    // for the example (limit action on client side). Take this as a broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
    return bodylist;
}
 
源代码20 项目: netty4.0.27Learn   文件: HttpUploadClient.java
/**
 * Multipart example
 */
private static void formpostmultipart(
        Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory,
        List<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception {
    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder =
            new HttpPostRequestEncoder(factory, request, true); // true => multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute from previous request in formpost()
    bodyRequestEncoder.setBodyHttpDatas(bodylist);

    // finalize request
    bodyRequestEncoder.finalizeRequest();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}