1. Download our Official Android App: Forums for Android!

new DatagramSocket(int/*port number*/) - "Address already in use"

Discussion in 'Android Development' started by Gregary Boyles, Oct 6, 2017.

  1. Gregary Boyles

    Thread Starter
    Rank:
    None
    Points:
    15
    Posts:
    30
    Joined:
    Oct 1, 2017

    Oct 1, 2017
    30
    0
    15
    The line of code that is throwing this exception is in bold text.

    The scenario is as follows.

    I am looping through stations 1 to m_nMaxStation (24) in function searchForStations().

    Each time I am broadcasting (10.0.0.255) the same string for each station.

    The broadcast string contains "request`<station number 1-24>`<IP address mobile device".

    Example "request`10`10.0.0.23`" (` character is just a delimiter used by the receiver to separate the bits of the string)

    After sending my request string 'waitResponse(final int nStation)' is called.

    This simply waits for a response from the station number specified in the request string.

    If a response is not received within the timeout then that station number is deemed to be inactive.

    But this is where the exception is thrown.

    The first call to waitResponse(final int nStation) results in no exception being thrown.

    But all subsequent calls throw the exception "Address already in use"

    How do I fix it?

    I have no idea despite searching google for a couple of hours.

    Code (Text):
    1.  
    2. package com.example.greg.irrigationcontroller;
    3.  
    4. import android.content.Context;
    5. import android.content.Intent;
    6. import android.net.wifi.WifiManager;
    7. import android.os.AsyncTask;
    8. import android.os.Bundle;
    9. import android.support.v7.app.AppCompatActivity;
    10. import android.view.View;
    11. import android.widget.Button;
    12. import android.widget.ProgressBar;
    13. import android.widget.TextView;
    14. import java.io.IOException;
    15. import java.net.DatagramPacket;
    16. import java.net.DatagramSocket;
    17. import java.net.InetAddress;
    18.  
    19.  
    20. /**
    21. * Created by Greg on 5/10/2017.
    22. */
    23.  
    24. public class CSearchAutoSolActivity extends AppCompatActivity implements View.OnClickListener
    25. {
    26.     @Override
    27.     protected void onCreate(Bundle savedInstanceState)
    28.     {
    29.         super.onCreate(savedInstanceState);
    30.         setContentView(R.layout.activity_search_auto_sol);
    31.  
    32.         m_app = ((CIrrigationApplication) getApplicationContext());
    33.         m_textviewResults = (TextView)findViewById(R.id.id_textview_results);
    34.         m_textviewTrying = (TextView)findViewById(R.id.id_textview_trying);
    35.         m_progress = (ProgressBar)findViewById(R.id.id_progressbar_search);
    36.         m_buttonStart = (Button)findViewById(R.id.id_button_start);
    37.         m_buttonStart.setOnClickListener(CSearchAutoSolActivity.this);
    38.         m_strUDPDelim = new String("`");
    39.         m_nUDPPort = 10002;
    40.     }
    41.  
    42.     @Override
    43.     public void onClick(View view)
    44.     {
    45.         Intent intent = null;
    46.  
    47.         switch (view.getId())
    48.         {
    49.             case R.id.id_button_start:
    50.                 m_buttonStart.setEnabled(false);
    51.                 m_searchtask = new CSearchTask();
    52.                 m_searchtask.execute();
    53.                 break;
    54.             case R.id.id_button_back:
    55.                 intent = new Intent(getApplicationContext(), CMainActivity.class);
    56.                 break;
    57.         }
    58.         if (intent != null)
    59.         {
    60.             finish();
    61.             startActivity(intent);
    62.         }
    63.     }
    64.  
    65.     protected CIrrigationApplication m_app;
    66.     TextView m_textviewResults, m_textviewTrying;
    67.     Button m_buttonStart;
    68.     ProgressBar m_progress;
    69.     String m_strUDPDelim;
    70.     int m_nUDPPort;
    71.     CSearchTask m_searchtask;
    72.  
    73.  
    74.     protected class CSearchTask extends AsyncTask<Void/**param type*/, Void/**progress type*/, String/**result type*/>
    75.     {
    76.         public CSearchTask()
    77.         {
    78.             m_strResults = new String();
    79.             m_strTrying = new String();
    80.             m_nProgress = 0;
    81.         }
    82.  
    83.         @Override
    84.         protected String doInBackground(Void...Void)
    85.         {
    86.             String strResult = new String("");
    87.  
    88.             searchForStations();
    89.  
    90.             return strResult;
    91.         }
    92.  
    93.         @Override
    94.         protected void onProgressUpdate(Void...param)
    95.         {
    96.             m_textviewResults.setText(m_strResults);
    97.             m_textviewTrying.setText(m_strTrying);
    98.             m_progress.setProgress(m_nProgress);
    99.         }
    100.  
    101.         @Override
    102.         protected void onPostExecute(String strResult)
    103.         {
    104.             m_buttonStart.setEnabled(true);
    105.             m_textviewTrying.setText("Finished");
    106.         }
    107.  
    108.         @Override
    109.         protected void onPreExecute()
    110.         {
    111.             if (m_app != null)
    112.             {
    113.                 m_wifiManag = (WifiManager) m_app.getSystemService(Context.WIFI_SERVICE);
    114.                 if ((m_wifiManag != null) && !m_wifiManag.isWifiEnabled())
    115.                     m_wifiManag.setWifiEnabled(true);
    116.             }
    117.         }
    118.  
    119.         protected boolean waitResponse(final int nStation)
    120.         {
    121.             boolean bResult = false;
    122.             String strMsg = new String("");
    123.             byte[] buffMsg = new byte[32];
    124.             DatagramPacket datagramPacket = new DatagramPacket(buffMsg, buffMsg.length);
    125.             DatagramSocket datagramSocket;
    126.  
    127.             try
    128.             {
    129.                 datagramSocket = new DatagramSocket(m_nUDPPort);
    130.             }
    131.             catch (IOException ioe)
    132.             {
    133.                 m_strResults = "new DatagramSocket() - " + ioe.getMessage();
    134.                 return bResult;
    135.             }
    136.             try
    137.             {
    138.                 datagramSocket.setSoTimeout(2000);
    139.                 datagramSocket.receive(datagramPacket);
    140.                 datagramSocket.close();
    141.             }
    142.             catch (IOException ioe)
    143.             {
    144.                 m_strResults = "DatagramSocket.receive(...) - " + ioe.getMessage();
    145.                 return bResult;
    146.             }
    147.             strMsg = new String(buffMsg, 0, datagramPacket.getLength());
    148.             if (bResult = (strMsg.length() > 0) && strMsg.contains("notify"))
    149.             {
    150.                 m_app.setStationActive(nStation, true);
    151.                 m_app.setStationIPAddress(nStation, datagramSocket.getInetAddress().getHostAddress());
    152.             }
    153.             return bResult;
    154.         }
    155.         protected void searchForStations()
    156.         {
    157.             if ((m_app != null) && (m_wifiManag != null) && m_wifiManag.isWifiEnabled() && (m_textviewResults != null) && (m_textviewTrying != null))
    158.             {
    159.                 InetAddress ipLocal;
    160.                 try
    161.                 {
    162.                     ipLocal = InetAddress.getLocalHost();
    163.                 }
    164.                 catch (IOException ioe)
    165.                 {
    166.                     m_strResults = "InetAddress.getLocalHost() - " + ioe.getMessage();
    167.                     publishProgress();
    168.                     return;
    169.                 }
    170.                 DatagramSocket datagramSocket;
    171.                 CIPAddress ipIPAddr = new CIPAddress(ipLocal.getHostAddress());
    172.                 try
    173.                 {
    174.                     datagramSocket = new DatagramSocket();
    175.                 }
    176.                 catch (IOException ioe)
    177.                 {
    178.                     m_strResults = "new DatagramSocket() - " + ioe.getMessage();
    179.                     publishProgress();
    180.                     return;
    181.                 }
    182.                 String strRequest = new String("request") + m_strUDPDelim, strMsg = new String();
    183.                 int nProgressInc = 100 / m_app.m_nMaxStations + 1;
    184.                 byte[] buffMsg;
    185.                 DatagramPacket datagramPacket;
    186.                 boolean bRespRec = false;
    187.                 InetAddress ia;
    188.                 try
    189.                 {
    190.                     ia = InetAddress.getByName(ipIPAddr.toBroadcast());
    191.                 }
    192.                 catch(IOException ioe)
    193.                 {
    194.                     m_strResults = "InetAddress.getByName(...) - " + ioe.getMessage();
    195.                     publishProgress();
    196.                     return;
    197.                 }
    198.                 for (int nStation = 1; nStation <= m_app.m_nMaxStations; nStation++)
    199.                 {
    200.                     m_strTrying = new String("Trying station ") + String.valueOf(nStation) + new String("...");
    201.                     publishProgress();
    202.                     strMsg = strRequest + String.valueOf(nStation) + m_strUDPDelim + ipIPAddr.toString() + m_strUDPDelim;
    203.                     buffMsg = strMsg.getBytes();
    204.  
    205.                     datagramPacket = new DatagramPacket(buffMsg, strMsg.length(), ia, m_nUDPPort);
    206.                     try
    207.                     {
    208.                         datagramSocket.send(datagramPacket);
    209.                     }
    210.                     catch (IOException ioe)
    211.                     {
    212.                         m_strResults = "DatagramSocket.send(...) - " + ioe.getMessage();
    213.                         publishProgress();
    214.                         return;
    215.                     }
    216.                     bRespRec = waitResponse(nStation);
    217.                     m_strResults += "Station " + String.valueOf(nStation) + ": ";
    218.                     if (bRespRec)
    219.                         m_strResults += "response received from " + m_app.getStationIPAddress(nStation) + "\n\n";
    220.                     else
    221.                         m_strResults += "no response\n\n";
    222.                     m_nProgress += nProgressInc;
    223.                 }
    224.             }
    225.         }
    226.  
    227.         WifiManager m_wifiManag;
    228.         String m_strResults, m_strTrying;
    229.         int m_nProgress;
    230.     }
    231. }
    232.  
     

    Advertisement

  2. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,873
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,873
    11,508
    1,988
    Male
    Software developer
    South West of England

Share This Page

Loading...