当我使用 JSch 时,我可以在套接字中使用自定义 OutputStream 吗?

问题描述 投票:0回答:1

当我使用JSch lib时,我可以使用自定义的

OutputStream
吗?

我想用 Google Proto 包装 JSch 消息。所以我必须使用自定义

OutputStream

我知道 JSch 可以设置自定义

SocketFactory
。所以我做了一个定制
SocketFactory

但是当会话连接时,它被冻结了。没成功。

我认为我的自定义

OutputStream
中断了与SSH协议的通信。

Session session = jSch.getSession( "root", "localhost", 55000 );
session.setPassword( "root" );
session.setConfig( "StrictHostKeyChecking","no" );
session.setSocketFactory( new SocketFactory() {
    @Override
    public Socket createSocket( String host, int port ) throws IOException, UnknownHostException {

        return new Socket( host, port );
    }

    @Override
    public InputStream getInputStream( Socket socket ) throws IOException {

        return socket.getInputStream();
    }

    @Override
    public OutputStream getOutputStream( Socket socket ) throws IOException {

        return new CustomOutputStream();
    }
} );
session.connect();

这是我的自定义流。

public class CustomOutputStream extends OutputStream {

    @Override
    public void write( int b ) throws IOException {
        byte[] a = new byte[] { (byte) b };
        write(a, 0, 1);
    }

    @Override
    public void write( byte[] b, int off, int len ) throws IOException {
        System.out.println( b.hashCode() );

        // Todo
        //  JschProto.JschContents jschContents = // JschProto.JschContents.newBuilder().setContent( ByteString.copyFrom( b ) )
        //              .setType( "t" )
        //              .build();

        super.write(b, off, len);
    }
}
java sockets io jsch outputstream
1个回答
2
投票

您的

CustomOutputStream
不使用插座。这是一个如何将其融入您的设计的示例。

public class CustomOutputStream extends OutputStream {
    private OutputStream innerStream;

    public CustomOutputStream(Socket socket) {
      this(socket.getOutputStream);
    }

    public CustomOutputStream(OutputStream delegate) {
      this.innerStream = delegate;
    }

    //TODO: Override more methods to delegate to innerStream

    @Override
    public void write( int b ) throws IOException {
        byte[] a = new byte[] { (byte) b };
        write(a, 0, 1);
    }


    @Override
    public void write( byte[] b, int off, int len ) throws IOException {


        System.out.println( b.hashCode() );

// Todo
    //  JschProto.JschContents jschContents = // JschProto.JschContents.newBuilder().setContent( ByteString.copyFrom( b ) )
//              .setType( "t" )
//              .build();

        innerStream.write(b, off, len);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.