i am trying to write a very simple socket program, what i basically want is that the client keeps listening for communication from the server, in a while(true) loop. now i also want client to be able to send some data back to the server in the middle of it listening.
The only solution i can think of is making a thread for the read and write, and interrupting the read thread everytime i have to do a write.
is there a better solution or is this the only way i can do this
You can use two threads. One for reading and one for writing. This way the write thread can write whenever it pleases (don't need to stop the read).
Another way to do it is to use setSoTimeout(timeoutMs)
on the socket before calling read. This will cause it to throw a SocketTimeoutException
if it takes longer than timeoutMs milliseconds to read, allowing you to then write as you please.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With