-3

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?

durron597
  • 31,968
  • 17
  • 99
  • 158
Farzane
  • 173
  • 1
  • 8

2 Answers2

4

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
-1

It seems you are referring to Asynchronous I/O, and although that is indeed achieved by using threads and sockets (as stated before), it is best done using NIO: http://en.wikipedia.org/wiki/New_I/O

It scales much better, and is event based, which is a much easier concept to grasp than multithreading, assuming you don't have much experience with IO and networking. And you can avoid some of its complexity by using Apache MINA: http://mina.apache.org/

javabeats
  • 1,082
  • 3
  • 12
  • 26
  • You're conflating three different things here. Concurrent I/O uses multiple threads in blocking mode and is supported by the `java.net` package. Non-blocking I/O is supported by NIO and Netty. Asynchronous I/O uses completion callbacks, not threads, and was introduced in JDK 1.7 as NIO2. – user207421 Nov 12 '12 at 22:55