如何使用Netty Reactor关闭TcpClient连接?

时间:2018-10-10 16:35:41

标签: java spring-boot reactor-netty

我正在尝试从netty Reactor.ipc.netty.tcp.TcpClient关闭TCP连接,但是我找不到简便的方法,没有“断开连接”,“停止”或“关闭”方法。谁能帮我?我正在使用react-netty.0.7.9.RELEASE库。

我的班级结构如下:

private TcpClient client;
private NettyOutbound out;

public Mono<? extends NettyContext> connect() {
    client = TcpClient.create(host, port);
    return client.newHandler(this::handleConnection)
            .log("newHandler");
}

private Publisher<Void> handleConnection(NettyInbound in, NettyOutbound out) {
    this.out = out;
    return out
            .neverComplete()    //keep connection alive
            .log("Never close");
}

public void disconnect() {
    client = TcpClient. //What can i put here to close the connection?
}

感谢您的帮助,非常感谢。

1 个答案:

答案 0 :(得分:0)

是的,很抱歉我以前没有发布过。 我要做的就是将tcp客户端的连接传递给字段变量,因此我可以使用dispose方法来处理连接。 这是代码。

private NettyOutbound out;
private Connection connection;

public ServerResponse connect() {
    return TcpClient.create()
        .host(tcpConfig.getHost())
        .port(tcpConfig.getPort())
        .handle(this::handleConnection)
        .connect()
        .flatMap(connection -> {
            this.connection = connection;
            log.info("Sending response to http client.");
            return ServerResponse.ok().build();
        });
}

private Publisher<Void> handleConnection(NettyInbound in, NettyOutbound out) {
    this.out = out;
    in.receive().asString(Charsets.ISO_8859_1)
        .log("In received")
        .subscribe(frameStr -> log.info(frameStr));
    return out
        .neverComplete()    //keep connection alive
        .log("Never close");
}

public void disconnect() {
    this.connection.dispose();
}