Java Reference
In-Depth Information
ceive() method is called, the client will pause until a message is received. You can
disable this feature by calling the DatagramChannel configureBlock-
ing(boolean) method and passing a false value. Next, the ByteBuffer is con-
verted to a string value and printed out by repositioning the buffer index at 0 using the
flip() method, and then pulling the text starting at index 0 to the last index into a
byte[] . Finally, be sure to disconnect the client when you're finished. That wraps up
the client code portion.
// Configure client to be passive and non.blocking
// client.configureBlocking(false);
client.receive(buffer);
// client pauses until a message is received... in this
case
System.out.println("Client Received Message:");
buffer.flip();
byte[] arr = new byte[buffer.remaining()];
buffer.get(arr, 0, arr.length);
System.out.println(new String(arr));
System.out.println("Disconnecting...performing a single
test pass only");
client.disconnect();
Note In the example to this recipe, a single pass is performed, and the client is then
disconnected. For extended listening, you would need a loop with a timeout and tests for
an ending state.
The server code is fairly basic. You can see that the MulticastServer class ex-
tends Thread . This means that this server application could run in a thread separate
from other code within an application. If there were another class that initiated the
MulticastServer class' run() method, it would run in a thread separate from the
class that initiated it. The run() method must exist in any class that extends Thread .
For more information regarding threading and concurrency, refer to Chapter 10 .
The bulk of the server code resides in the run() method. A new InetAddress
object is created using the same IP address that the client registered with in order to
join the multicast group. The same port number is also declared in the server code, and
these two objects will be used later in the code block to send the message. A new Da-
Search WWH ::




Custom Search