簡體   English   中英

從TCP客戶端中的服務器接收消息並在TextView中進行設置

[英]Receive message from server in TCP Client and set it in TextView

我在嘗試可視化從TCP服務器發送的消息作為對我的TCP客戶端的響應時遇到了一些麻煩

這是我的Client.java代碼

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

}

這是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);
        }
    }
};

}

所以我想做的是從服務器接收消息,並在名為msgServer的TextView中將其在help.java活動中可視化,並將其設置為靜態。 實際上,我不知道必須將哪個值歸因於help.msgServer.setText()以及將其放在MainActivity中的位置。

通過在MainActivity中的AsyncTask中設置以下代碼進行修復:

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

在onProgressUpdate方法中。 因此,我確定了從哪里可以獲取服務器發送的消息的正確位置,該消息包含在:

價值觀

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM