Search code examples
javaandroidtcptcpclient

Receive message from server in TCP Client and set it in TextView


I'm having some troubles while trying to visualize the message send from the TCP Server as response to my TCP Client

Here is my Client.java code

public class Client {


public static String SERVER_IP; //server IP address
public static String ipp;
public static final int SERVER_PORT = 4444;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;

/**
 * Constructor of the class. OnMessagedReceived listens for the messages received from server
 */
public Client(OnMessageReceived listener) {
    mMessageListener = listener;
}



/**
 * Sends the message entered by client to the server
 *
 * @param message text entered by client
 */
public void sendMessage(String message) {
    if (mBufferOut != null && !mBufferOut.checkError()) {
        mBufferOut.println(message);
        mBufferOut.flush();
    }
}

/**
 * Close the connection and release the members
 */
public void stopClient() {

    mRun = false;

    if (mBufferOut != null) {
        mBufferOut.flush();
        mBufferOut.close();
    }

    mMessageListener = null;
    mBufferIn = null;
    mBufferOut = null;
    mServerMessage = null;
}

public void run() {

    mRun = true;

    try {
        //here you must put your computer's IP address.
        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

        Log.e("TCP Client", "C: Connecting...");

        //create a socket to make the connection with the server
        Socket socket = new Socket(serverAddr, SERVER_PORT);

        try {

            //sends the message to the server
            mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            //receives the message which the server sends back
            mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));


            //in this while the client listens for the messages sent by the server
            while (mRun) {

                mServerMessage = mBufferIn.readLine();

                if (mServerMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(mServerMessage);
                }

            }

            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");

        } catch (Exception e) {

            Log.e("TCP", "S: Error", e);

        } finally {
            //the socket must be closed. It is not possible to reconnect to this socket
            // after it is closed, which means a new socket instance has to be created.
            socket.close();
        }

    } catch (Exception e) {

        Log.e("TCP", "C: Error", e);

    }

}

//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
    public void messageReceived(String message);
}

}

While here is the MainActivity :

public class MainActivity extends AppCompatActivity {
Server server;
static Client client;
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
static String ipp;
static String trm;
static DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
        "Via Beniamino Disraeli, 17,\n" +
        "42124 Reggio Emilia \n" +
        "Telefono: 0522 / 38 32 22 \n" +
        "Fax: 0522 / 38 32 72 \n" +
        "Partita IVA, Codice Fiscale \n" +
        "Reg. Impr. di RE 00168780351 \n" +
        "Cap. soc. € 50.000,00 i.v. \n" + "" +
        "REA n. RE-107440 \n" +
        "presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Utils.darkenStatusBar(this, R.color.colorAccent);
    server = new Server(this);
    myDB = DataBaseHandler.getInstance(this);

    msg = (TextView) findViewById(R.id.msg);
    log = (TextView) findViewById(R.id.log_avviso);
    settings = (ImageButton) findViewById(R.id.impo);
    helps = (ImageButton) findViewById(R.id.aiut);
    allerts = (ImageButton) findViewById(R.id.msge);
    home = (ImageButton) findViewById(R.id.gab);
    terminale = (TextView) findViewById(R.id.terminal);
    indr = (TextView) findViewById(R.id.indr);

    final Cursor cursor = myDB.fetchData();
    if (cursor.moveToFirst()) {
        do {
            indr.setText(cursor.getString(1));
            terminale.setText(cursor.getString(2));
            Client.SERVER_IP = cursor.getString(1);
            trm = cursor.getString(2);
        } while (cursor.moveToNext());
    }



    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());


    startConnection.postDelayed(runnableConnection,5000);
    startMessage.postDelayed(runnableMessage,5500);

    cursor.close();
    server.Parti();


    home.setOnClickListener(new View.OnClickListener() {
                                int counter = 0;
        @Override
        public void onClick(View view) {
                                    counter++;
                                    if (counter == 10) {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                        builder.setCancelable(true);
                                        builder.setMessage(s1);
                                        builder.show();
                                        counter = 0;
                                    }
        }
    });

    settings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
            startActivity(impostazioni);
        }
    });

    helps.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent pgHelp = new Intent(getApplicationContext(), help.class);
            startActivity(pgHelp);
        }
    });

    allerts.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Server.count = 0;
            SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.clear();
            editor.apply();
            msg.setVisibility(View.INVISIBLE);
            Intent pgAlert = new Intent(getApplicationContext(), allert.class);
            startActivity(pgAlert);
        }
    });

}

@Override
protected void onDestroy() {

    super.onDestroy();
    server.onDestroy();
}

public static class ConnectTask extends AsyncTask<String, String, Client> {

    @Override
    protected Client doInBackground(String... message) {


        client = new Client(new Client.OnMessageReceived() {
            @Override

            public void messageReceived(String message) {

                messageReceived(message);
            }
        });
        client.run();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

        Log.d("test", "response " + values[0]);


    }
}

static Handler startConnection = new Handler();
static Runnable runnableConnection = new Runnable() {
    @Override
    public void run() {

        new ConnectTask().execute("");
    }
};

static Handler startMessage = new Handler();
static Runnable runnableMessage = new Runnable() {
    @Override
    public void run() {
        final Cursor cursor = myDB.fetchData();
        if (cursor.moveToFirst()) {
            do {
                Client.SERVER_IP = cursor.getString(1);
                trm = cursor.getString(2);
            } while (cursor.moveToNext());
        }
        if (client != null) {
            client.sendMessage(ipp + "#" + trm);
        }
    }
};

}

So what i'm trying to do is receive message from the server and visualize it in help.java activity in a TextView called msgServer set as static. Actually i don't know which value i have to attribute to the help.msgServer.setText() and where to put it in MainActivity.


Solution

  • Fixed by setting in AsyncTask in MainActivity following code:

    msgServer.setTextColor(Color.parseColor("#00FF00"));
    msgServer.setText("ONLINE");
    

    in the onProgressUpdate method. So i identified the right place from where i can get the message sent by the server, the message is contained in:

    values

    .