2017-01-23 1 views
0

시작시 SSDP를 사용하여 서버에 연결하고 IP 주소를 검색하는 앱을 개발 중입니다. SSDP 클래스는 나에 의해 개발되지 않았으므로 거기에 어떤 리팩토링 제안도 열려 있지만이 질문에 대해서는 SSDP를 사용하여 서버를 계속 찾고있는 논리를 구현하려고합니다. 충돌이나 제한 시간 예외를 피할 수 있습니다. 던지기에서.SSDP를 사용하여 Android의 로컬 네트워크에서 장치를 검색하는 방법은 무엇입니까?

현재 내 발표자 클래스는 서버의 응답을 얻기 위해 개인 AsyncTask를 클래스를 사용 (모타 또는 주석에 OTA 역라고도 함) :

:

private class SearchAction extends AsyncTask<Void,Void,String>{ 
    Context context; 

    SearchAction(Context context){ 
     this.context = context; 
    } 

    protected void onPreExecute(){ 
     view.changeVisibility(true); 
    } 

    @Override 
    protected String doInBackground(Void... params) { 
     //Get IP Address from MOTA Station 
     SSDP ssdp = new SSDP(); 
     String ip = ssdp.request(); 
     Log.d(TAG,"IP Address is: "+ ip); 
     return ip; 
    } 

    @TargetApi(Build.VERSION_CODES.KITKAT) 
    protected void onPostExecute(String ip_address){ 
     Log.d(TAG, "IP address is: " + ip_address); 


     if (Objects.equals(ip_address, "")) { 

      view.changeVisibility(false); 
      // TODO: give choice to user to enter IP address manually 
     }else { 
      //otherwise go to MainActivity directly 
      Intent intent = new Intent(context, Main2Activity.class); 
      intent.putExtra("IP", ip_address); 
      view.navigateToMainActivity(intent); 

     } 
    } 
} 

SSDP 클래스 그렇게 보이는 공용 클래스 SSDP {

public String tag = "SSDP"; 

//m-search string for specific OTA board 
private static final String query = 
     "M-SEARCH * HTTP/1.1\r\n" + 
       "HOST: 239.255.255.250:1900\r\n"+ 
       "MAN: \"ssdp:discover\"\r\n"+ 
       "MX: 1\r\n"+ 
       "ST: urn:schemas-upnp-org:device:MediaServer:1\r\n"+ // Use for OTA Board 
       //"ST: ssdp:all\r\n"+ // Use this for all UPnP Devices 
       "\r\n"; 
private static final int port = 1900; 

//ssdp to find IP address from server 
public String request(){ 
    //response is to contain the server response in String type 
    //initialize send data and receive data in bytes 
    String response=""; 
    byte[] sendData = new byte[1024]; 
    byte[] receiveData = new byte[1024]; 
    //transfer m-search string in bytes 
    sendData = query.getBytes(); 
    //wrap m-search data, multicast address and port number to the send package 
    DatagramPacket sendPacket = null; 
    try { 
     sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("239.255.255.250"), port); 
    } catch (UnknownHostException e) { 
     Log.d(tag,"Unknown Host Exception Thrown after creating DatagramPacket to send to server"); 
     e.printStackTrace(); 
    } 
    //create socket to transport data 
    DatagramSocket clientSocket = null; 
    try { 
     clientSocket = new DatagramSocket(); 
    } catch (SocketException e) { 
     Log.d(tag, "Socket Exception thrown when creating socket to transport data"); 
     e.printStackTrace(); 
    } 
    //send out data 
    try { 
     if (clientSocket != null) { 
      //time out is important 
      clientSocket.setSoTimeout(10000); 
      clientSocket.send(sendPacket); 
     } 
    } catch (IOException e) { 
     Log.d(tag, "IOException thrown when sending data to socket"); 
     e.printStackTrace(); 
    } 
    // receive data 
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
    try { 
     if (clientSocket != null) { 
      clientSocket.receive(receivePacket); 
     } 
    } catch (IOException e) { 
     Log.d(tag,"IOException thrown when receiving data"); 
     e.printStackTrace(); 
    } 
    //the target package should not be empty 
    //try three times 

    for (int i =0; i<3; i++){ 
     Log.d(tag,"Checking target package to see if its empty on iteration#: "+i); 
     response = new String(receivePacket.getData()); 
     Log.d(tag,"Response contains: "+response); 
     if (response.contains("Location:")){ 
      break; 
     } 
    } 


    String adress = ""; 
    //filter IP address from "Location" 
    Matcher ma = Pattern.compile("Location: (.*)").matcher(response); 
    if (ma.find()){ 
     adress+=ma.group(1); 
     adress = adress.split("/")[2].split(":")[0]; 
    } 

    return adress; 

} 
} 

내 질문은, 내가 반복 요청()를 호출 할 수있는 방법 (또는 요청의 특정 부분을()) I는 서버로부터 응답을 얻을 때까지?

답변

0

Timer Task를 사용하여 5 초마다 AsyncTask를 수행했습니다.

private Runnable ssdpTimerTask = new Runnable() { 
     @Override 
     public void run() { 
      startStationSearch(); 
      Log.d(TAG,"Running SSDP search - iteration: "+ssdpIteration); 
      ssdpIteration++; 
      mHandler.postDelayed(ssdpTimerTask,5000); 
     } 
    }; 
관련 문제