Sun's j2se implementation of the j2me Datagram appears to be a bit broken:
javax.microedition.io.DatagramConnection dc = createDatagramConnection();
javax.microedition.io.Datagram datagram = (javax.microedition.io.Datagram)datagramConnection.newDatagram( 1000 );
datagram.reset(); datagram.setLength( 1000 ); datagramConnection.receive( datagram );
datagram.getClass().toString().equals( "class com.sun.cldc.io.j2se.datagram.DatagramObject" );
String fromString = datagram.getAddress();
fromString.equals( "datagram://localhost:127.0.0.1" );
I had expected "datagram://127.0.0.1:{PortNum}"
The Datagram interface is sufficiently vague to allow the current behaviour. It was probably intentional because a client "typically" sends from a randomly assigned port and receives on the "well-known" port for whatever protocol. So there is "no need" to know what port the client sent from, maybe it would just lead to "confusion".
However I would like my server know which port to send back to, esp when doing loopback, as the client and server cannot listen to the same port. My client sends and receives on the same UDP port. I would prefer to not have to hard-code and keep track of assigned ports.
Here is Sun's source code.
public String getAddress() {
InetAddress addr = dgram.getAddress();
if(addr == null) {
return null;
} else {
return "datagram://" + addr.getHostName() + ":" + addr.getHostAddress();
}
}
by contrast setAddress uses the expected format:
public void setAddress(String addr) throws IOException {
if(!addr.startsWith("datagram://")) {
throw new IllegalArgumentException("Invalid datagram address"+addr);
}
String address = addr.substring(11);
try {
host = Protocol.getAddress(address);
port = Protocol.getPort(address);
dgram.setAddress(InetAddress.getByName(host));
dgram.setPort(port);
} catch(NumberFormatException x) {
throw new IllegalArgumentException("Invalid datagram address"+addr);
} catch(UnknownHostException x) {
throw new IllegalArgumentException("Unknown host "+addr);
}
}
The result is that the procedure
outgoingDatagram.setAddress( incomingDatagram.getAddress() );
can't work.
My question is, can I patch the j2se libraries so getAddress() reports the sending port?