Socket Exception - address already in use - how do I stop it.

  • Replies:0
Greg Boyles
  • Forum posts: 6

Oct 15, 2017, 11:41:15 AM via Website

What will itit take to STOP android studio from throwing this exception in my app????

setReuseAddress(true) does not work.

Creating an empty DatagramSocket object, calling setReuseAddress(true) and then trying to use bind(...) to attach the DatagramSocket object to a port does not work either.

I.E. If a try...
DatagramSocket socket = new DatagrapSocket();
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(m_nPort));

Then the last line of code throws an invalid argument exception.

@Override
public void run()
{
DatagramSocket socketSend = null, socketRec = null;
CBuff buff = new CBuff(m_nBuffSize);
DatagramPacket packet = new DatagramPacket(buff.get(), buff.size());
String strMsg = new String();

//sendUpdateState("Connecting...");

try
{
    InetAddress inetaddressDest = InetAddress.getByName(m_strDestIPAddr);

    // Send request
    buff = new CBuff(m_strMsg.getBytes());
    packet = new DatagramPacket(buff.get(), buff.size(), inetaddressDest, m_nPort);

    socketSend = new DatagramSocket(m_nPort);
    socketSend.setBroadcast(true);

    //sendUpdateState("Connected...");
    socketSend.send(packet);
    socketSend.close();
    //sendUpdateState("Send socket closed!");

    //sendUpdateState("Message ('" + m_strMsg + "') sent to " + m_strDestIPAddr + " on port " + String.valueOf(m_nPort));

    // Get response
    //sendUpdateState("Waiting for response.");
    socketRec = new DatagramSocket(m_nPort);
    socketRec.setReuseAddress(true);
    socketRec.setSoTimeout(2000);
    buff.New(m_nBuffSize);
    packet = new DatagramPacket(buff.get(), buff.size());
    socketRec.receive(packet);
    socketRec.close();
    //sendUpdateState("Receive socket closed!");
}
catch (SocketTimeoutException e)
{
    e.printStackTrace();
    sendUpdateState("No response!");
}
catch (SecurityException e)
{
    e.printStackTrace();
    sendUpdateException(m_strMsg + "Security exception - " + e.getMessage() + ", " + m_strDestIPAddr);
}
catch (IllegalArgumentException e)
{
    e.printStackTrace();
    sendUpdateException(m_strMsg + "Illegal argument exception - " + e.getMessage() + ", " + m_strDestIPAddr);
}
catch (SocketException e)
{
    e.printStackTrace();
    sendUpdateException(m_strMsg + "Socket exception - " + e.getMessage() + ", " + m_strDestIPAddr);
}
catch (IOException e)
{
    e.printStackTrace();
    sendUpdateException(m_strMsg + "IO exception - " + e.getMessage() + ", " + m_strDestIPAddr);
}
finally
{
    strMsg = new String(packet.getData(), 0, packet.getLength());
    if (strMsg.length() > 0)
    {
        sendUpdateMessageReceived("Message setn: '" + m_strMsg + "'\n\n" + strMsg);
    }
}

}

— modified on Oct 15, 2017, 12:19:37 PM

Reply