2011-01-25 27 views
0

我在Android中有一個TCP客戶端(Eclipse中的Java程序)。該服務器是Eclipse中運行的另一個Java應用程序。在這種情況下一切正常。手機中的Android TCP客戶端在與外部服務器通信時出現問題

當我嘗試從我的同事的應用程序(在Rhapsody中開發,我認爲C++)接收到消息時,我只在他的應用程序關閉後才收到消息,而不是在他的應用程序正在運行併發送消息時收到消息。你有什麼想法爲什麼發生這種情況?

謝謝你在這方面的時間和精力。

乾杯, 馬杜

Java服務器是這樣的:

public class TCPSendServer implements Runnable{ 
    public static final String SERVERIP = "192.168.178.24"; 
    public static final int SERVERPORT = 1200; 
    //static Category cat = Category.getInstance(TCPSendServer.class.getName()); 
    //cat.debug("Start of main()"); 

    public void run() { 
     try { 
      System.out.println("S: Connecting...");    
      ServerSocket serverSocket = new ServerSocket(SERVERPORT); 
      String msg = "<MSG><N>shiftDirection</N><V>1</V></MSG>"; 
      String msg1 = "<MSG><N>vehicleSpeed</N><V>120</V></MSG>"; 
      String msg2 = "SD<!N><V>0<!V><!MSG>"; 

      //while (true) { 
       Socket client = serverSocket.accept(); 

        try { 
         System.out.println("S: Sending: '" + msg + "'"); 
         PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);      
         Thread.sleep (5000); 
         out.println(msg); 
         Thread.sleep (5000); 
         //out.println(msg2); 
         Thread.sleep (5000); 
         out.println(msg1); 
         //out.flush(); 
         System.out.println("S: Sent."); 
         System.out.println("S: Done."); 
        } catch(Exception e) { 
         System.out.println("S: Error"); 
         e.printStackTrace(); 
        } //finally { 
         // client.close();       
        //} 
      //} 
     } catch (Exception e) { 
      System.out.println("S: First try error"); 
      e.printStackTrace(); 
     } 
    } 

    public static void main (String a[]) { 
     Thread desktopServerThread = new Thread(new TCPSendServer()); 
     desktopServerThread.start(); 
    } 
} 

Android客戶端代碼: 主要活動:

public class TCPListen extends Activity implements TCPListener { 
    private TextView mTitle; 
    public String data[] = new String[2]; 

    /** Called when the activity is first created. */ 
    @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      //setContentView(R.layout.main);    

      // Set up the window layout 
      requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
      setContentView(R.layout.main); 
      getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); 

      // Set up the custom title 
      mTitle = (TextView) findViewById(R.id.title_left_text); 
      mTitle.setText(R.string.app_name); 
      mTitle = (TextView) findViewById(R.id.title_right_text); 

      //TcpServiceHandler handler=new TcpServiceHandler(this); 
      //handler.execute("192.168.178.24"); 

      TcpServiceHandler handler = new TcpServiceHandler(this,this); 
      Thread th = new Thread(handler); 
      th.start();    
     }   

     public String[] callCompleted(String source){ 
       Log.d("TCP", "Std parser " + source); 
       mTitle.setText(source); 
       //String data[] = new String[2]; 

       //if (source.matches("<MSG><N>.*</N><V>.*</V></MSG>")) {   
        Document doc = null; 
        try{ 
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
         DocumentBuilder db = dbf.newDocumentBuilder(); 
         doc = (Document) db.parse(new ByteArrayInputStream(source.getBytes())); 
         NodeList n = doc.getElementsByTagName("N"); 
         Node nd = n.item(0); 
         String msgName = nd.getFirstChild().getNodeValue(); 
         NodeList n1 = doc.getElementsByTagName("V"); 
         Node nd1 = n1.item(0); 
         String tmpVal = nd1.getFirstChild().getNodeValue(); 
         data[0] = msgName; 
         data[1] = tmpVal; 
         Log.d("TCP", "Inside Std parser " + data[0] + " " + data[1]); 
         //actionOnData(data[0], data[1]); 
         } 
        catch(Exception e){ 
        e.printStackTrace(); 
       } 
       Log.d("TCP", "Just outside Std parser " + data[0] + " " + data[1]); 
       return data; 
       //} else Log.d("TCP", "Message in wrong format " + source); 
       //mTitle.setText("Message in wrong format " + source); 
       //return data; 
      } 

接口:

public interface TCPListener { 
    public String[] callCompleted(String msg); 
} 

TCPServiceHandler:

public class TcpServiceHandler implements Runnable { 
    TCPListener _listener;    
    private Activity _act; 
    public TcpServiceHandler(TCPListener listener, Activity act){  
     _listener = listener; 
     _act = act; 
    }   

    public synchronized void run() { 
     // TODO Auto-generated method stub   
     //if(socket==null){  
      try { 
       InetAddress serverAddr = InetAddress.getByName("192.168.178.25"); 
       Socket socket = new Socket(serverAddr, 1200); 
     // 
       while(true){ 
        try {       
         BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
         final String str = in.readLine(); 
         this._act.runOnUiThread(new Runnable(){ 

         public void run() { 
          _listener.callCompleted(str); 
          }         
         });             
        } 
        catch(Exception e){ 
         e.printStackTrace(); 
        } 
       } 
      } catch (UnknownHostException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
    }  
} 

回答

0

這是這裏的SERVERIP問題。你是從本地機器上的模擬器運行你的應用程序嗎?您的模擬器不是您局域網的一部分。仿真器運行在虛擬路由器/防火牆服務之後,將其與開發計算機的網絡接口和設置以及互聯網隔離。

因此,您需要使用網絡重定向或端口轉發來實現與位於單獨計算機上的服務器的通信。

如果您在設備上運行應用程序,那麼您可以將該設備作爲網絡的一部分,然後它應該可以工作。

+0

我在Android手機上運行客戶端代碼(HTC Desire)。如果服務器是在Eclipse中運行的Java應用程序,那麼我可以接收此服務器在我的Android手機上發送的數據。當我嘗試從另一個應用程序(例如abc,可以認爲是充當服務器)接收數據時,我可以連接到應用程序,但無法接收任何數據。如果我嘗試從仿真器連接客戶端,而不是將真正的電話連接到abc,那麼只有在abc關閉後,才能接收abc發送的數據,而不是在運行和發送數據時。真實手機&abc不工作 - 連接已建立,但沒有數據 – 2011-01-25 10:55:54

0

至少目前已有解決方案。我使用readLine()來讀取套接字的內容,這需要\ n或\ r或類似的字符,直到它返回內容爲止。當服務器和客戶端都使用Java時,這對我來說不是問題。但是當客戶端不得不從另一個應用程序接收消息時,我遇到了這個問題。只需將\ n添加到其他應用發送的消息結尾即可解決問題。