Java Reference
In-Depth Information
datagramConn.send(myDatagram);
To receive datagrams, you need to create a datagram server connection. For that purpose, you again use
the Connector.open() method, but this time without specifying the hostname of the machine.
Instead, you just give the local port number your server will listen to:
DatagramConnection serverDatagramConn =
(DatagramConnection)Connector.open ("datagram://:1234");
In order to receive a datagram, you need to call the receive() method, which blocks until a
datagram is received. Before you call the receive() method, you need to create a datagram object
that is passed to this method. The receive() method fills the given object from the datagram
received. Now let's assume that you expect the client to send a datagram containing a "hello
world" string consisting of 11 bytes. To create a datagram that is able to hold the complete buffer,
you need to create an empty datagram with a buffer size of at least 11 bytes using the following line of
code:
Datagram receivedDatagram = serverDatagramConn.newDatagramConn (11);
Finally, you need to call the receive() method of the DatagramConnection to receive the
datagram sent from the client and convert the contained buffer back to a String :
serverDatagramConn.receive(receivedDatagram);
String helloWorldString = new String(receivedDatagram.getData());
The helloWorldString variable should now contain the "Hello World" String that was
sent from the client.
As a real-world example, we will again use the server time-a.nist.gov . It supports not only
socket connections, but also the datagram time protocol specified in RFC868. This protocol returns a
32-bit binary number that represents the time in seconds since January 1, 1900.
If you want to compare the server time to the local time, you need to convert the server time to the
usual Java format, which is measured in milliseconds since January 1, 1970. Thus, you must subtract
the 2,208,988,800 seconds between 1.1.1900 and 1.1.1970 from the server time, and then multiply the
result by 1,000 in order to convert the seconds to milliseconds.
The following code example establishes a corresponding DatagramConnection to the time server
datagram://time-a.nist.gov:37 :
try {
Connection connection = Connector.open ("datagram://time-
a.nist.gov:37");
// converting the Connection to a DatagramConnection
DatagramConnection datagramConnection =
(DatagramConnection)connection;
// creating a new datagram in order to request the time from the
server
Datagram datagram = datagramConnection.newDatagram
(datagramConnection.getNominalLength());
// sends the datagram to the server
datagramConnection.send (datagram);
// for the response that is sent from the server
Search WWH ::




Custom Search