I am trying to create a server that receives UDP packets and responds with UDP messages. However, I can't seem to get it to bind to a port. Here's my constructor for the class:
public UDPServer() throws IOException {
myGUI = new ServerGUI();
myClientList = new ArrayList<ClientInfo>();
DatagramChannel channel = DatagramChannel.open();
mySocket = channel.socket();
//mySocket = new DatagramSocket(null);
//mySocket.setReuseAddress(true);
//mySocket.bind(new InetSocketAddress("localhost", Constants.SERVER_PORT_NUM));
myPortNum = mySocket.getPort();
myIP = mySocket.getInetAddress();
System.out.println(myPortNum + " " + myIP.toString());
}
I have tried both the channel method and the commented out method, and I even used this method to try and find an open port:
private DatagramSocket createNewSocket() throws IOException {
for (int i = Constants.MIN_PORT_NUM; i < Constants.MAX_PORT_NUM; i++){
try {
System.out.println(i);
return new DatagramSocket(i);
} catch (IOException e){
continue; // try next port
}
}
throw new IOException("No free port found");
}
But I've had no luck so far. The portNum keeps coming up as -1
and the IP is null
. Any ideas what could be going on here?
EDIT: When I run the following in debug mode and scroll over mySocket to see what values it contains, it says that:
bound = true
closed = false
connectedAddress = null
connectedPort = -1
But when I run mySocket.getLocalPort()
, it returns a valid port number. What's going on here?
Here's the code:
public UDPServer() throws IOException {
myGUI = new ServerGUI();
myClientList = new ArrayList<ClientInfo>();
mySocket = new DatagramSocket(Constants.SERVER_PORT_NUM);
mySocket.setReuseAddress(true);
myPortNum = mySocket.getLocalPort();
myIP = mySocket.getInetAddress();
System.out.println(mySocket);
}
You don't need to do this. Just create it with the non-args constructor, or specify port zero. The system will allocate a free port for you.