Java Code Examples for io.netty.channel.Channel#flush()

The following examples show how to use io.netty.channel.Channel#flush() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebsocketSinkConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example 2
Source File: TelNettyHandler.java    From hasor with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 3
Source File: ClientConnectionImpl.java    From pravega with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 4
Source File: Responses.java    From consulo with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 5
Source File: HardwareLoginHandler.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 6
Source File: UaTcpStackServer.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
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();
        }
    }
}
 
Example 7
Source File: DefaultChannelGroup.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelGroup flush(ChannelMatcher matcher) {
    for (Channel c: nonServerChannels.values()) {
        if (matcher.matches(c)) {
            c.flush();
        }
    }
    return this;
}
 
Example 8
Source File: AbstractHttp2ClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 9
Source File: ResponseRouter.java    From tchannel-java with MIT License 5 votes vote down vote up
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();
        }
    }
 
Example 10
Source File: ProxyEndpoint.java    From zuul with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 11
Source File: ReadingWidgetsWorker.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
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();
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example 12
Source File: HttpUploadClient.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
}
 
Example 13
Source File: HttpUploadClient.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source File: Subscription.java    From etherjar with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example 15
Source File: RequestorSupport.java    From azeroth with Apache License 2.0 4 votes vote down vote up
@Override
public void request(Channel channel) {
    List<Object> requests = writeRequests(channel.alloc());
    requests.forEach(channel::write);
    channel.flush();
}
 
Example 16
Source File: NettyClientServerCommunicationSystemServerSide.java    From protect with MIT License 4 votes vote down vote up
private void closeChannelAndEventLoop(Channel c) {
	c.flush();
	c.deregister();
	c.close();
	c.eventLoop().shutdownGracefully();
}
 
Example 17
Source File: MessageServiceImpl.java    From withme3.0 with MIT License 4 votes vote down vote up
private void sendMessage(Channel channel, String message) {
    channel.write(new TextWebSocketFrame(message));
    channel.flush();
}
 
Example 18
Source File: ClientResponseWriter.java    From zuul with Apache License 2.0 4 votes vote down vote up
@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);
    }
}
 
Example 19
Source File: HttpUploadClient.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
}
 
Example 20
Source File: NettyClientServerCommunicationSystemServerSide.java    From library with Apache License 2.0 4 votes vote down vote up
private void closeChannelAndEventLoop(Channel c) {
	c.flush();
	c.deregister();
	c.close();
	c.eventLoop().shutdownGracefully();
}