Mix NIO with IO

Usually you have one tcp port connected and several connections to them. At least there are usually more connections as connected ports. My thing is different: I want to bind a lot of ports and usually do not have (or at least very few) connections.

Therefore, I want to use NIO to receive incoming connections.

However, I need to transfer the accepted connections to the existing jsch ssh library. This requires IO sockets instead of NIO sockets, it generates one (or two) stream (s) for each connection. But it is perfect for me.

Now I thought the following lines would produce the same result:

Socket a = serverSocketChannel.accept().socket();
Socket b = serverSocketChannel.socket().accept();
SocketChannel channel = serverSocketChannel.accept();
channel.configureBlocking( true );
Socket c = channel.socket();
Socket d = serverSocket.accept();

However, the functions getInputStream()and getOutputStream()returned sockets seem different. Only if the socket was received using the last call, jsch can work with it. In the first three cases, he fails (and I'm sorry: I don't know why).

So is there a way to convert such a socket?

+3
source share
2 answers

Input and output streams returned by sockets received from SocketChannels are internally synchronized over the channel at some points. Therefore, you cannot use them for full-duplex protocols such as SSH, because the system will shut down. The same applies to streams converted from channels through the Channels class (which corresponds to the first case).

+2

:

final SocketAddress serverAddr =
    new InetSocketAddress(
        bind_address,
        server_port
    );

final ServerSocketChannel serverChannel = ServerSocketChannel.open( );

serverChannel.socket( ).bind(
    serverAddr,
    backlog
);

final SocketChannel socketChannel = serverChannel.accept( );

final Socket socket = socketChannel.socket( );

final OutputStream out = socket.getOutputStream( );

final InputStream in = socket.getInputStream( );

blocking.

, /.

, , NIO

-1

Source: https://habr.com/ru/post/1739391/


All Articles