Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat could be causing this socket not to find a port?
    text
    copied!<p>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:</p> <pre><code>public UDPServer() throws IOException { myGUI = new ServerGUI(); myClientList = new ArrayList&lt;ClientInfo&gt;(); 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()); } </code></pre> <p>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:</p> <pre><code>private DatagramSocket createNewSocket() throws IOException { for (int i = Constants.MIN_PORT_NUM; i &lt; 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"); } </code></pre> <p>But I've had no luck so far. The portNum keeps coming up as <code>-1</code> and the IP is <code>null</code>. Any ideas what could be going on here?</p> <p>EDIT: When I run the following in debug mode and scroll over mySocket to see what values it contains, it says that:</p> <pre><code>bound = true closed = false connectedAddress = null connectedPort = -1 </code></pre> <p>But when I run <code>mySocket.getLocalPort()</code>, it returns a valid port number. What's going on here?</p> <p>Here's the code:</p> <pre><code>public UDPServer() throws IOException { myGUI = new ServerGUI(); myClientList = new ArrayList&lt;ClientInfo&gt;(); mySocket = new DatagramSocket(Constants.SERVER_PORT_NUM); mySocket.setReuseAddress(true); myPortNum = mySocket.getLocalPort(); myIP = mySocket.getInetAddress(); System.out.println(mySocket); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload