Java Reference
In-Depth Information
int size = ( bytesToSend > 512 ) ? 512 : bytesToSend ;
dp . setData ( bigarray , bytesSent , size );
}
On the other hand, this strategy requires either a lot of confidence that the data will in
fact arrive or, alternatively, a disregard for the consequences of its not arriving. It's rel‐
atively difficult to attach sequence numbers or other reliability tags to individual packets
when you take this approach.
public void setAddress(InetAddress remote)
The setAddress() method changes the address a datagram packet is sent to. This might
allow you to send the same datagram to many different recipients. For example:
String s = "Really Important Message" ;
byte [] data = s . getBytes ( "UTF-8" );
DatagramPacket dp = new DatagramPacket ( data , data . length );
dp . setPort ( 2000 );
int network = "128.238.5." ;
for ( int host = 1 ; host < 255 ; host ++) {
try {
InetAddress remote = InetAddress . getByName ( network + host );
dp . setAddress ( remote );
socket . send ( dp );
} catch ( IOException ex ) {
// skip it; continue with the next host
}
}
Whether this is a sensible choice depends on the application. If you're trying to send to
all the stations on a network segment, as in this fragment, you'd probably be better off
using the local broadcast address and letting the network do the work. The local broad‐
cast address is determined by setting all bits of the IP address after the network and
subnet IDs to 1. For example, Polytechnic University's network address is 128.238.0.0.
Consequently, its broadcast address is 128.238.255.255. Sending a datagram to
128.238.255.255 copies it to every host on that network (although some routers and
firewalls may block it, depending on its origin).
For more widely separated hosts, you're probably better off using multicasting. Multi‐
casting actually uses the same DatagramPacket class described here. However, it uses
different IP addresses and a MulticastSocket instead of a DatagramSocket . We'll dis‐
cuss this further in Chapter 13 .
public void setPort(int port)
The setPort() method changes the port a datagram is addressed to. I honestly can't
think of many uses for this method. It could be used in a port scanner application that
tried to find open ports running particular UDP-based services such as FSP. Another
possibility might be some sort of networked game or conferencing server where the
clients that need to receive the same information are all running on different ports as
Search WWH ::




Custom Search