How can I send and receive data simultaneously in socket programming in Java using multithreaded?

advertisements

I'm new to Java and trying to write a program using Datagram socket to send & receive packets between a client and a server. The problem is that when the cursor arrives at the receive() line, it gets stuck there until a packet arrives. During this time, how can I send data to the other side? In the other word, how can I have it send and receive concurrently using datagram socket?


You need threads (or NIO/netty, but that's much more advanced).

Basically blocking IO (as the name implies) blocks current thread on every read/write operation if it can't be handled at a time. Thus you need a second thread to handle writes. Every good Java socket tutorial will include an example of a multithreaded server.