2012-06-25 4 views
0

현재 터미널에서 실행되는 간단한 Java 프로그램 인 Android and Server 간의 소켓 통신을 개발 중입니다. 내가 StackOverflow에 Similar Problem에 게시물을 볼 수있는 문제를 찾기 위해 인터넷에서 검색하고Android에서 송수신 소켓 구현

IInputConnectionWrapper showStatusIcon on inactive InputConnection 

: 나는 응용 프로그램을 닫을 때 경고가 항상 로그 캣에 표시가 제외 상황이 잘 진행된다. 차이점은 내 프로그램에서 정보를 잘 보내고받을 수 있다는 것입니다. 이 비슷한 문제에 대한 대답은 연결이 닫히지 않는다는 것입니다. 작동 후 socket.close();으로 전화하지 않았다는 의미입니까? 이는보다 복잡한 구현 문제를 야기합니다.

우선, 하나의 정적 소켓을 수신하여 서버에 보내고 싶습니다. 뭔가를 전송할 때마다 소켓을 닫지 않을 수도 있기 때문에 청취자가 작업을 마친 후에 닫을 수 있습니다.

client = new Socket(mServerName, mport); 
out = new DataOutputStream(client.getOutputStream()); 
inFromServer = new InputStreamReader(client.getInputStream()); 
reader = new BufferedReader(inFromServer); 

그리고 그 전체 과정이있을 수 있습니다 :

상세 코드는 나뿐만 생성자에서 연결을 초기화

아래에 게시됩니다.

public void sendRequest(int type, int what1, int what2, Object data) 
{ 
    try{ 
     if(client.isConnected()) 
     { 
      out.writeUTF(encoded(type,what1,what2,data) + "\n");    
     } 
    }catch(IOException e){ 
     Log.e(TAG, "IOException at SendRequest"); 
     e.printStackTrace(); 
    } 
} 

리스너를 새로운 스레드 :

try {  
     String line = null; 
     while ((line = reader.readLine()) != null) 
     { 
      ReceiveHandler(line); 
     } 
    } catch (IOException e) { 
     Log.e(TAG, "IOException at StartListen"); 
     e.printStackTrace(); 
    }finally{ 
     try { 
     // The Only Place that I close the Socket 
      inFromServer.close(); 
      out.close(); 
      reader.close(); 
      client.close(); 
     } catch (IOException e) { 
      Log.e(TAG, "Close Socket with IOException " + e.toString()); 
      e.printStackTrace(); 
     } 
    } 

내 질문은 :

인가 뭔가를

나는 다음과 같은 기능으로 서버에 안드로이드에서 전송 썼다 내 구현에 문제가 있거나 더 나은 방법이 있습니까?

도움을 주셔서 감사합니다.

답변

1

당신이 networ를 진단 할 수있는 도구가 k 관련 문제는 Android 기기와 에뮬레이터에서 모두 발생합니다. 문제를 조금 더 추적하는 데 도움이 될 수 있습니다. ARO 도구는 오픈 소스이며 여기에서 이용하실 수 있습니다. http://developer.att.com/developer/forward.jsp?passedItemId=9700312

0

나는이 고객의 어떠한 사용 여부에 수 있을지 모르겠습니다 ...하지만 난 ... 당신에게

클라이언트 측 코드 내가 클라이언트 서버 통신에 사용되는 코드를 제공하고있다 :

public class ClientWala { 

    public static void main(String[] args) throws Exception{ 

     Boolean b = true; 
    Socket s = new Socket("127.0.0.1", 4444); 

    System.out.println("connected: "+s.isConnected()); 


    OutputStream output = s.getOutputStream(); 
    PrintWriter pw = new PrintWriter(output,true); 

    // to write data to server 
    while(b){ 

     if (!b){ 

      System.exit(0); 
     } 

     else { 
      pw.write(new Scanner(System.in).nextLine()); 
     } 
    } 


    // to read data from server 
    InputStream input = s.getInputStream(); 
    InputStreamReader isr = new InputStreamReader(input); 
    BufferedReader br = new BufferedReader(isr); 
    String data = null; 

    while ((data = br.readLine())!=null){ 

     // Print it using sysout, or do whatever you want with the incoming data from server 

    } 




    } 
} 

서버 측 코드 :

import java.io.* 
import java.net.*; 


public class ServerTest { 

    ServerSocket s; 

    public void go() { 

     try { 
      s = new ServerSocket(44457); 

      while (true) { 

       Socket incoming = s.accept(); 
       Thread t = new Thread(new MyCon(incoming)); 
       t.start(); 
      } 
     } catch (IOException e) { 

      e.printStackTrace(); 
     } 

    } 

    class MyCon implements Runnable { 

     Socket incoming; 

     public MyCon(Socket incoming) { 

      this.incoming = incoming; 
     } 

     @Override 
     public void run() { 

      try { 
       PrintWriter pw = new PrintWriter(incoming.getOutputStream(), 
         true); 
       InputStreamReader isr = new InputStreamReader(
         incoming.getInputStream()); 
       BufferedReader br = new BufferedReader(isr); 
       String inp = null; 

       boolean isDone = true; 

       System.out.println("TYPE : BYE"); 
       System.out.println(); 
       while (isDone && ((inp = br.readLine()) != null)) { 

        System.out.println(inp); 
        if (inp.trim().equals("BYE")) { 
         System.out 
           .println("THANKS FOR CONNECTING...Bye for now"); 
         isDone = false; 
         s.close(); 
        } 

       } 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       try { 
        s.close(); 
       } catch (IOException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } 
       e.printStackTrace(); 
      } 

     } 

    } 

    public static void main(String[] args) { 

     new ServerTest().go(); 

    } 

} 
+0

감사합니다. 그러나 프로그램에서 콘솔을 경청하여 정보를 보내고 있습니다. 내가 원하는 것은 다른 클래스에서 메시지 보내기 함수를 호출 할 수 있다는 것입니다. 이것에 대한 아이디어가 있습니까? 모두 똑같은 감사합니다! – Fei