Java Reference
In-Depth Information
import java.nio.* ;
import java.nio.channels.* ;
public class UDPDiscardServerWithChannels {
public final static int PORT = 9 ;
public final static int MAX_PACKET_SIZE = 65507 ;
public static void main ( String [] args ) {
try {
DatagramChannel channel = DatagramChannel . open ();
DatagramSocket socket = channel . socket ();
SocketAddress address = new InetSocketAddress ( PORT );
socket . bind ( address );
ByteBuffer buffer = ByteBuffer . allocateDirect ( MAX_PACKET_SIZE );
while ( true ) {
SocketAddress client = channel . receive ( buffer );
buffer . flip ();
System . out . print ( client + " says " );
while ( buffer . hasRemaining ()) System . out . write ( buffer . get ());
System . out . println ();
buffer . clear ();
}
} catch ( IOException ex ) {
System . err . println ( ex );
}
}
}
Sending
The send() method writes one datagram packet into the channel from a ByteBuffer
to the address specified as the second argument:
public int send ( ByteBuffer src , SocketAddress target ) throws IOException
The source ByteBuffer can be reused if you want to send the same data to multiple
clients. Just don't forget to rewind it first.
The send() method returns the number of bytes written. This will either be the number
of bytes that were available in the buffer to be written or zero, nothing in between. It is
zero if the channel is in nonblocking mode and the data can't be sent immediately.
Otherwise, if the channel is not in nonblocking mode, send() simply waits to return
until it can send all the data in the buffer.
Example 12-16 demonstrates with a simple echo server based on channels. Just as it did
in Example 12-15 , the receive() method reads a packet. However, this time, rather
than logging the packet on System.out , it returns the same data to the client that sent
it.
Search WWH ::




Custom Search