手机中的Android TCP Client与外部服务器通信时出现问题

时间:2011-01-25 10:16:35

标签: android sockets communication external tcpclient

我在Android中有一个TCP客户端(Eclipse中的Java程序)。该服务器是另一个在Eclipse中运行的Java应用程序。在这种情况下一切正常。

当我尝试从我的同事的应用程序(在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();  
             }  
     }    
 }

2 个答案:

答案 0 :(得分:0)

这是SERVERIP的问题。您是否在本地计算机上使用模拟器运行应用程序?您的模拟器不是LAN的一部分。仿真器运行在虚拟路由器/防火墙服务后面,该服务将其与开发机器的网络接口和设置以及互联网隔离开来。

因此,您需要使用网络重定向或端口转发来实现与位于单独计算机上的服务器的通信。

如果您在设备上运行应用程序,那么您可以将该设备作为网络的一部分,然后它应该可以正常工作。

答案 1 :(得分:0)

至少目前已有解决方案。我使用readLine()来读取套接字的内容,这需要\ n或\ r或类似的字符,直到它返回内容。当服务器和客户端都使用Java时,这对我来说不是问题。但是当客户端不得不从不同的应用程序接收消息时,我遇到了这个问题。只需在另一个应用程序发送的消息末尾添加\ n即可克服它。