33
There are some points to note about using datagrams:
• Only datagrams obtained from the connection may be passed in send or receive calls on the
connection. You cannot obtain a datagram from one connection and use it with another.
• A connection opened with a specific address can only be used to send to that address.
Attempts to send to other addresses will result in an exception.
• It is permitted to open a server connection and a client connection on the same machine
using the same port numbers. All incoming datagrams for that port will be routed to the
server connection.
•
Currently, closing a server connection also closes any client connections on the same port.
Using system allocated ports
Most applications use perhaps one or two ports with fixed numbers (remember that each SPOT can
open many connections on the same port, as long as they are to different remote SPOTs). However,
some applications need to open variable numbers of connections to the same remote SPOT, and for
such applications, it is convenient to ask the library to allocate free port numbers as required. To do
this, simply exclude the port number from the url. So, for example:
RadiogramConnection conn =
(RadiogramConnection)Connector.open("radiogram://0014.4F01.0000.0006");
This call will open a connection to the given remote SPOT on the first free port. To discover which
port has been allocated, do
byte port = conn.getLocalPort();
You can open server radiogram connections in a similar way:
RadiogramConnection serverConn = (RadiogramConnection)Connector.open("radiogram://");
The same port allocation process works with radiostream connections. However, for radiostream
connections, the port number is allocated only after either an input or output stream is opened. So,
for example
RadiostreamConnection conn =
(RadiostreamConnection)Connector.open("radiostream://0014.4F01.0000.0006:10");
// byte port = conn.getLocalPort(); // this would throw an exception as the
// port has not been allocated yet.
RadioInputStream is = (RadioInputStream)conn.openInputStream();
byte port = conn.getLocalPort(); // now the port can be accessed from the connection...
port = is.getLocalPort(); // ...or from the input stream.
Adjusting connection properties
The
RadiostreamConnection
and
RadiogramConnection
classes provide a method for setting a
timeout on reception. For example:
RadiostreamConnection conn =
(RadiostreamConnection)Connector.open("radiostream://0014.4F01.0000.0006:100");
conn.setTimeout(1000); // wait 1000ms for receive