这是indexloc提供的服务,不要输入任何密码
Skip to content

How to use the Channel obtained by channel_direct_tcpip to read and write data separately? #325

@tzfun

Description

@tzfun

Usually when proxying a TCP network, not all requests are responded to. It is possible that two or even multiple requests will result in a response. How can I use the read and write methods in the Channel obtained by channel_direct_tcpip to achieve this effect? ​​Currently, I can only achieve "one request must have one response". I don't know how to do it.

I hope that the read and write methods of this Channel can handle their own things separately, just like the sender and receiver obtained by onshot::channel().

This is my current code. The problem with the code is that read_channel often times out.

pub fn test_ssh_tunnel_with_ssh2() {
    let mut session = Session::new().unwrap();
    let tcp = TcpStream::connect(SSH_ADDR).unwrap();
    session.set_tcp_stream(tcp);
    session.handshake().unwrap();

    session.set_keepalive(false, 5);

    let private_key = Path::new(SSH_KEY);
    session.userauth_pubkey_file("tz", None, private_key, Some(SSH_KEY_PASSPHRASE)).unwrap();

    let session = Arc::new(session);

    let listener = net::TcpListener::bind("127.0.0.1:5000").unwrap();
    for stream in listener.incoming() {
        let mut stream = stream.unwrap();

        let ssh_session = Arc::clone(&session);
        thread::spawn(move || {
            let mut channel = ssh_session.channel_direct_tcpip("127.0.0.1", 2379, None).unwrap();
            loop {
                let (request, size) = read_stream(&mut stream);
                if size <= 0 {
                    break;
                }

                channel.write_all(&request[..size]).unwrap();
                channel.flush().unwrap();
               
                //  This always times out when there is no response to this request
                let (response, size) = read_channel(&mut channel);
                if size <= 0 {
                    break
                }
                stream.write_all(&response[..size]).unwrap();
                stream.flush().unwrap();
            }
            channel.close().unwrap();
        });
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions