Java Reference
In-Depth Information
{
dgs.receive(dgp);
System.out.println(new String(data));
dgs.send(dgp);
}
}
catch (IOException ioe)
{
System.err.println("i/o
error:
"+ioe.getMessage());
}
}
}
Listing 9-4 ' s main() method first creates a DatagramSocket object and binds
the socket to port 10000 on the local host. It then invokes DatagramSocket 's int
getSendBufferSize() and int getReceiveBufferSize() methodstoget
the values of the SO_SNDBUF and SO_RCVBUF socket options, which are then output.
Note Socketsareassociatedwithunderlyingplatformsendandreceivebuffers,and
their sizes are accessed by calling getSendBufferSize() and getReceiver-
BufferSize() . Similarly, their sizes can be set by calling DatagramSocket 's
void setReceiveBufferSize(int size) and void setSendBuffer-
Size(int size) methods.Althoughyoucanadjustthesebuffersizestoimprove
performance,there'sapracticallimitwithregardtoUDP.ThemaximumsizeofaUDP
packetthatcanbesentorreceivedis65,507bytesunderIPv4—it'sderivedfromsub-
tracting the 8-byte UDP header and 20-byte IP header values from 65,535. Although
youcanspecifyasend/receivebufferwithagreatervalue,doingsoiswastefulbecause
thelargestpacketisrestrictedto65,507bytes.Also,attemptingtosend/receiveapack-
et greater than 65,507 bytes (regardless of buffer size) results in IOException .
main() next instantiates DatagramPacket in preparation for receiving a data-
grampacketfromaclientandthenechoingthepacketbacktotheclient.Itassumesthat
packets will be 100 bytes or less in size.
Finally, main() entersaninfiniteloopthatreceivesapacket,outputspacketcontent,
andsendsthepacketbacktotheclient—theclient'saddressinginformationisstoredin
DatagramPacket .
Search WWH ::




Custom Search