开发者

Android TCP Client in phone has problems in communicating with external server

开发者 https://www.devze.com 2023-02-06 20:11 出处:网络
I have a TCP Client in Android (Java program in Eclipse). The server was another Java app running in Eclipse. Everything works fine in this situation.

I have a TCP Client in Android (Java program in Eclipse). The server was another Java app running in Eclipse. Everything works fine in this situation.

When I tried to receive message from my colleague's app (developed in Rhapsody and I think C++), I receive the message only after his app is closed and not while his app is running and sending messages. Do you have any idea why this happens?

Thank you for the time and effort on this.

Cheers, Madhu

The java server is like this:

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();
    }
}

The Android client code: Main activity:

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;
            }

Interface:

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 Inp开发者_JS百科utStreamReader(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();  
             }  
     }    
 }


This is problem with the SERVERIP here. Are you running your app from an emulator in your local machine? Your emulator is not part of your LAN. Emulator runs behind a virtual router/firewall service that isolates it from your development machine's network interfaces and settings and from the internet.

So you need to use network redirections or port forwarding to achieve communication with the server which is on a separate machine.

If you are running the app on a device then you can make that device as part of your network and then it should work.


There has been a solution, at least for the time being. I use readLine() to read contents of sockets and this expects \n or \r or similar characters until it returns the contents. This was not the issue for me when both server and client were in Java. But when the client had to receive messages from a different app, I faced this problem. It was overcome by just adding \n to the end of message sent by the other app.

0

精彩评论

暂无评论...
验证码 换一张
取 消