cracq
cracq

Reputation: 91

How to send and receive messages on the client?

I'm building a very simple app which consist of a client in which the user input a string that is sent to the server. Then, once the server has received the message, it sends back the same to the client. My problem is that I'm getting an error on the client when I try to read the message sent by the server.

Once the socket is opened, the following snippet shows how the client tries to send and receive messages:

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                      .getOutputStream())),true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

out.println(message);

if (in.readLine()!=null)


    response=in.readLine();

I' getting a strictMode$AndroidBlockGuardPolicy.onNetwork() exception when reading the "in" variable (in.readLine())

The server side is as follows:

while ((line = in.readLine()) != null) {
                            final String line2=line;
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    serverStatus.setText(line2);
                                }
                            });
                            out.println("Message received:"+line2);

The only thing I want is to send a message to the client confirming that a message on the server has been received. Another problem I'm facing is that a need to allow time for the server to received the message, read it and send it back to the client, so the client should wait for maybe a second. What could I use for this purpose? Would the sleep method be appropriate?

Thread.sleep(1000);

or

systemClock.sleep(1000);

Thanks in advance

[UPDATE]

this is the code for the client:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_client);

    serverIp = (EditText) findViewById(R.id.server_ip);
    connectPhones = (Button) findViewById(R.id.connect_phones);
    connectPhones.setOnClickListener(connectListener);

    messageServer = (EditText) findViewById(R.id.message);
    communicatePhones = (Button) findViewById(R.id.send_message);
    messageServer.setVisibility(View.GONE);
    communicatePhones.setVisibility(View.GONE);


}

private OnClickListener connectListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        if (!connected) {
            serverIpAddress = serverIp.getText().toString();
            if (!serverIpAddress.equals("")) {
                Thread cThread = new Thread(new ClientThread());
                cThread.start();
            }
        }
    }
};

public class ClientThread implements Runnable {

    public void run() {
        try {
            Log.d("ClientActivity", serverIpAddress);
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            socket = new Socket(serverAddr, ServerActivity.SERVERPORT);

            handler.post(new Runnable() {
                  @Override
                  public void run() {
                      serverIp.setVisibility(View.GONE);
                      connectPhones.setVisibility(View.GONE);
                      messageServer.setVisibility(View.VISIBLE);
                      communicatePhones.setVisibility(View.VISIBLE);

                      communicatePhones.setOnClickListener(communicateListener);

                      mensajeRecibido = (TextView) findViewById(R.id.mensaje_recibido);
                      mensajeRecibido.append(response);
                  }
            });
            //socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }

    private OnClickListener communicateListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            message = messageServer.getText().toString();
            if (!serverIpAddress.equals("")) {
                try {
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                            .getOutputStream())), true);        

                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    out.println(message);
                    Log.d("ClientActivity", "C: Sent.");
                    //Thread.sleep(6000);
                    SystemClock.sleep(2000);
                  /*  handler.postDelayed(new Runnable() { 
                         public void run() { 
                              my_button.setBackgroundResource(R.drawable.defaultcard); 
                         } 
                    }, 2000); */
                    if (in.readLine()!=null)
                        response=in.readLine();

                } catch (IOException e) {
                    Log.e("ClientActivity", "S: Error", e);
                }              
            }
        }
    };
}

}

Where should I create the OnClickListener object for communicateListener? I've tried to place it inside the run method and I got errors like unknown communicateListener variable or invalid private modifier.

Upvotes: 0

Views: 202

Answers (1)

Sharp80
Sharp80

Reputation: 186

You do know that you are not suppose to access GUI elements via threads which are not main thread?

And its bad practice to access network via main thread... communicateListener looks to me all wrong... is it running in GUI thread or in ClientThread? it suppose to run in GUI thread as its onClick event - but the logic inside looks like network thread.

Your main thread (GUI thread) should send a message to a network thread (you can use handler to do it, or just call a method of the network thread, which can be a data member of the main thread - but the onClick should be implemented in main thread!).

Upvotes: 1

Related Questions