Read from AsyncTcpSocket in separate Thread #263
-
Hi. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi, @iEAmi
However, if you absolutely need to read from the A code could look something like this: Eventloop eventloop = Eventloop.getCurrentEventloop();
ChannelSupplier<ByteBuf> channelSupplier = ChannelSupplier.ofSocket(socket);
Thread thread = new Thread(() -> {
try (InputStream inputStream = ChannelSuppliers.channelSupplierAsInputStream(eventloop, channelSupplier)) {
// read from 'inputStream'
}
});
thread.start(); Although, the performance will be worse than reading directly inside the Eventloop thread. I would suggest reading the data from the socket inside the Eventloop thread, and then passing all the read data to a separate thread for processing. |
Beta Was this translation helpful? Give feedback.
Hi, @iEAmi
AsyncTcpSocket
is meant to be used inside anEventloop
. AnEventloop
runs in a single thread, so every operation onAsyncTcpSocket
should be performed from within that thread. This is the main idea behind usingAsyncTcpSocket
in the first place.However, if you absolutely need to read from the
AsyncTcpSocket
in a separate thread, you can use a converter. First, you would need to convert the socket to aChannelSupplier
. Then you can convert aChannelSupplier
to a regularInputStream
which can be used from a non-Eventloop thread.A code could look something like this: