Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket read and write simultaneously [closed]

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

like image 995
yahh Avatar asked Oct 09 '12 20:10

yahh


1 Answers

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.

like image 182
CrazyCasta Avatar answered Oct 11 '22 06:10

CrazyCasta