2

I have a client which can send some information to a server via TCP :

    public class IR {

    private String host; //server IP address indicated here, I deleted it for posting here
    private int port = 6789;

    private String sentence;
    private String reply;

    public IR(String type) {
        try {

            Socket clientSocket = new Socket(host,port); //IP du server ("localhost" pour un server local) et port utilisé

            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));


                Gson gson = new GsonBuilder().create();
                FileReader file = new FileReader("data/userInfo.json");
                String json = "";
                int i = 0;
                while ((i = file.read()) != -1)
                    json += (char)i;
                User user = gson.fromJson(json, User.class);
                String user_id = user.getID();
                int bus_id = user.getBusID();

                sentence = "alerte " + type + " " + user_id + " " + bus_id;
                System.out.println("SENTENCE: " + sentence);
                outToServer.writeBytes(sentence + '\n');
                reply = inFromServer.readLine();
                System.out.println("ANSWER: " + reply);

            clientSocket.close();

        }
        catch (Exception io) {
            System.out.println("Connection refusée: arrêt");
        }
    }
}

I am calling this in my android application : I have a button which use this method when I'm clicking on it :

public void signalerComplet(View view)
{
    client = new IR("complet");
    Toast.makeText(this, "envoyé", Toast.LENGTH_SHORT).show();
}

But my server doesn't get anything . Though, I ma sure that my client works when I'm using it not in my android application . Could somebody say to me what I am missing here ?

EDIT after getting Hector's help : the server gets my "bloubloubloub" but I get an android.os.NetworkOnMainThreadException on the "int size = in.read(data);" ...

private Socket socket;

  public void signalerComplet(View view)
{
    PrintWriter out = null;
    InputStream in=null;

    byte[] data = new byte[5120];

    try {
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    out.println("bloubloubloub" + '\n');
    out.flush();

    try {
        in = socket.getInputStream();
        int size = in.read(data);
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    Log.e("data from server", data.toString());
}
2
  • put the line in = socket.getInputStream(); after out.flush();
    – hcarrasko
    Jan 12, 2016 at 17:10
  • did it (and updated post) . Still the same exception at in.read(data)... Jan 12, 2016 at 18:41

4 Answers 4

2

type.equals(null) will always be false as if the variable type actually holds a null value it will throw a NullPointerException as there is no method equals for the null value. Therefore the if body will never execute.

The correct way to match if a variable is null is by the == operator.

if (type == null) {
  // do this
} else {
  // do that
}

equals() on a String should be used to compare against another String.

3
  • Vitor Viola said the same thing to me, but as I answered, solving this little problem didn't solve my bigger problem :/ (though, this "if" thing was really dumb x) ) Jan 12, 2016 at 13:47
  • I don't understand you answer, why you write this? and how it solves the question?
    – hcarrasko
    Jan 12, 2016 at 13:47
  • Original question did not specify he was calling a network operation on the onCreate() method, just that he was not getting anything on the server. He was not getting it because it's code was not executing, therefore my answer. Anyhow you shouldn't be executing (networks) operations at all on a constructor. @BénédicteLagouge @Hector Jan 12, 2016 at 15:57
1

In Android you can't just put all this code in the onCreate method (for example) and run it, because you can't start a proccess that blocks the main thread, in this case Socket clientSocket = new Socket(host,port); will block the main thread and you app will crashes. You need do this tcp communication using threads. Please try this code and follow this algorithm:

Create this inner class, this will excecute the socket connection using threads:

class ClientThread implements Runnable {
        @Override
        public void run() {
            try {
                socket = new Socket(ipServer, portServer);
            } catch (UnknownHostException e1) {
                threadMsg("Connection fails");
            } catch (IOException e1) {
                threadMsg("Connection fails");
            }
        }
    }

In onCreate Method call this

new Thread(new ClientThread()).start();

And in you send button should put something like this:

PrintWriter out = null;
try {
     out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
} catch (IOException e) {
     e.printStackTrace();
}
out.println(messageToServer);
out.flush();

And this should send the string to server socket. Also you need add some basic validations.

EDIT: To get data from server, add this code in a new onClick button method:

byte[] data = new byte[5120];
try {
   in = socket.getInputStream();
   int size = in.read(data);
   // see the received data from server in you LogCat
   Log.e("data from server", data.toString());
} catch (Exception e) {
   e.printStackTrace();
}

Hope it helps.

4
  • 1
    Thanks, it was really useful ! Jan 12, 2016 at 14:33
  • Sorry to ask more question, but here we are sending something to the server . Could you give me an example of method (activated when a button is clicked or wathever) for getting back information ? Do I use a PrintWriter object again ? Jan 12, 2016 at 14:59
  • @BénédicteLagouge My edit should work, I can't test it in this moment, let me know if works fine
    – hcarrasko
    Jan 12, 2016 at 15:13
  • I tried, but I'm getting a android.os.NetworkOnMainThreadException on the in.read(data) . I updated on the first post the code of the function which should be called by clicking the button . 'Hope you can see something I did wrong . Jan 12, 2016 at 15:39
0

When you do:

 client = new IR("complet");

You will fall at the else statement in your IR constructor which does nothing despite to close connection.

2
  • Ok, you're right...but it still doesn't work . I edited my first post (just deleted the if/else statement, I won't need it anyway...) . Do you have any clues about what the problem could be ? I've tried several things, but I have no idea . While using log debugging, it seems that it doesn't do ANYTHING of what is in the "try" . Jan 12, 2016 at 13:42
  • In android, you need to implement an AsyncTask to do the communication with the server. You cannot have this kind of behavior in your main thread. Jan 12, 2016 at 14:38
-1

Here is what I've done . Thanks again to Hector for his help . It works great . Anything which could be "magnified" would be appreciated . :)

public class SignalerProblemeActivity extends Activity {


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.signaler_probleme);
}

public void signalerComplet(View view)
{
    new Thread(new CompletThread()).start();
    Toast.makeText(this, "Signalement de bus complet envoyé", Toast.LENGTH_SHORT).show();
}

class CompletThread implements Runnable {
    @Override
    public void run() {
        Socket socket=null;
        User u = new User("momo",12);
        String sentence="alerte complet "+u.getID()+u.getBusID();

        try {
            //CREATION SOCKET
            socket=new Socket("123.456.789.10",6789);

            //SENDING
            PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
            out.println(sentence);

            //GETTING
            BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String mstr=br.readLine();

            Log.e("CLIENT",mstr);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch(Exception e)
        {
            Log.e("CLIENT",e.toString());
        }

    }
}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.