views:

68

answers:

2

is multi-threading is possible in a simple java server using udp connectionless protocol? pls give an example!!

+2  A: 

Yes, it's possible through the use of the DatagramChannel class in java.nio. Here's a tutorial (It does not address the multithreading, but that is a separate issue anyway).

Michael Borgwardt
+1  A: 

Multi-threading is actually simpler with UDP because you don't have to worry about connection state. Here is the listen loop from my server,

           while(true){

                    try{
                            byte[] buf = new byte[2048];

                            DatagramPacket packet = new DatagramPacket( buf, buf.length, address );

                            socket.receive( packet );
                            threadPool.execute( new Request( this, socket, packet ));

           .......

The threadPool is a ThreaPoolExecutor. Due to the short-lived nature of UDP sessions, thread pool is required to avoid the overhead of repeatedly thread creation.

ZZ Coder