Android TCP client does not work

Asked

Viewed 35 times

0

Good Afternoon,

I’m creating an application in android studio to send a string from smartphone to pc.

My application has the following code:

public void Send_Command(View v) {

  testClass();

  Toast.makeText(getApplicationContext(), "Comando Enviado!", Toast.LENGTH_LONG).show();

}

public static void testClass() {
  Thread cThread = new Thread(new ClientThread());
  cThread.start();
}

public static class ClientThread implements Runnable {

  String results = "";

  public void run() {
    try {
      InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
      System.out.println("C: Connecting...");
      while (true) {
        results = "";
        try {
          Socket socket = new Socket("192.168.1.77", 8888);
          BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
          BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
          out.write("Test");
          out.flush();
          String inMsg = "";
          boolean b = false;
          while (!b) {
            inMsg = in .readLine();
            if (inMsg != "")
              b = true;
          }
          socket.close();
          System.out.println("C: Closed.");
        } catch (Exception e) {
          System.out.println("S: Error" + e.toString());
        }
      }
    } catch (Exception e) {
      System.out.println("C: Error" + e);
    }
  }
}

I put Send_message on onClick of a button and when I run the application with a C# server open on the pc nothing happens, but if I run the same android studio code in eclipse, with the same server in C# open, the connection is established and the string sent.

I’m new to programming for android, so it’s possible I’m making some basic mistake, however I don’t know where.

Does anyone know where the mistake might be ?

Thank you

  • What do you mean "when I run the application with a C# server open on the pc nothing happens"? Are you running the application on mobile and pointing to the PC that is as server? Checked the rules of firwall and whether the device is on the same network as the PC?

  • Yes, the devices are on the same network, and the IP address of the PC with the server is the same that I indicate in the App. The PC firewall that has the server is disabled.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.