客户端如何不断接受来自服务器的消息

时间:2019-06-23 08:25:01

标签: java android sockets server client

我希望不断接收来自服务器的消息,因此我将MainActivity设置为implements Runnable,并覆盖run()

run()中,我有一个无限循环来接收消息。另外,我在onCreate()中启动线程。

但是,当我在模拟器中运行该应用程序时,会引发异常,这与泄漏的窗口有关。

代码:

public class MainActivity extends AppCompatActivity implements Runnable {

    @Override
    public void run() {
        try {
            while (true) {
                if (client.isConnected()) {
                    if (!client.isInputShutdown()) {
                        if ((content = br.readLine()) != null) {
                            content += "\n";
                            handler.sendEmptyMessage(0x123);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button_send);
        editText = (EditText) findViewById(R.id.editText);
        textView = (TextView) findViewById(R.id.textView);

        showInputDialog();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = editText.getText().toString();
                editText.setText("");
                Message msg = Message.obtain();
                msg.obj = str;
                msg.what = CHANGE_TEXT;
                msg.arg1 = 1;
                msg.arg2 = 1;
                handle.sendMessage(msg);

                new MsgThread(str);
            }
        });
        new Thread(Mainactivity.this).start();
    }
}

0 个答案:

没有答案