Troubleshooting guide

127
7: Creating connections
Task Steps
Before opening a datagram connection,
verify that the BlackBerry® device is in
a wireless coverage area.
>Use the CoverageInfo class and CoverageStatusListener interface of the
net.rim.device.api.system package to make sure that the BlackBerry device is in a
wireless coverage area.
Even though the CoverageInfo class and the CoverageStatusListener interface can
determine if the BlackBerry device that your application is on is in a wireless coverage area,
they cannot guarantee that a subsequent network connection will be successful.
Open a datagram connection. 1. Invoke Connector.open(), specifying udp as the protocol.
2. Cast the returned object as a DatagramConnection object.
(DatagramConnection)Connector.open("udp://host:dest_port[;src_port]/
apn");
where:
host is the host address in dotted ASCII-decimal format.
dest-port is the destination port at the host address (optional for receiving messages).
src-port is the local source port (optional).
apn is the network APN in string format.
Receive datagrams from all ports at the
specified host.
> Omit the destination port in the connection string.
Open a datagram connection on a non-
GPRS network.
> Specify the source port number, including the trailing slash mark.
For example, the address for a CDMA network connection would be udp://
121.0.0.0:2332;6343/.
You can send and receive datagrams on the same port number.
Create a datagram. >Invoke DatagramConnection.newDatagram().
Datagram outDatagram = conn.newDatagram(buf, buf.length);
Add data to a datagram. >Invoke Datagram.setData().
byte[] buf = new byte[256];
outDatagram.setData(buf, buf.length);
Send data on the datagram connection. >Invoke send() on the datagram connection.
conn.send(outDatagram);
If an application attempts to send a datagram on a datagram connection and the recipient is
not listening on the specified source port number, an
IOException is thrown. Make sure that
the application implements exception handling.
Receive data on the datgram connection. >Invoke receive() on the datagram connection. Since the receive() method blocks other
operations until it receives a data packet, use a timer to retransmit the request or close the
connection if a reply does not arrive.
byte[] buf = new byte[256];
Datagram inDatagram = conn.newDatagram(buf, buf.length);
conn.receive(inDatagram);
Extract data from a datagram. >Invoke getData(). If you know the type of data that you are receiving, convert the data to
the appropriate format.
String received = new String(inDatagram.getData());
Close the datagram connection. >Invoke close() on the input and output streams and on the datagram connection object.