Android - 从套接字服务器获取消息

时间:2017-08-30 16:46:53

标签: android

我正在尝试在客户端上显示服务器消息(我在服务器端使用Python)。但是这个代码有问题。 当我添加此代码我的应用程序崩溃,但当我删除代码它将工作

此代码的问题

MainActivity.this.runOnUiThread(new Runnable(){

                        @Override
                        public void run() {
                            text.setText(message);
                        }
                    });

MainActivity.java

public class MainActivity extends Activity {


    private Socket socket;
    private TextView text;
    private static final int SERVERPORT = 12;
    private static final String SERVER_IP = "192.168.0.1";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

    public void onClick(View view) {
        try {
            text = (TextView) findViewById(R.id.text2);
            EditText et = (EditText) findViewById(R.id.EditText01);
            String str = et.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class ClientThread implements Runnable {
        String message = "";
        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                socket = new Socket(serverAddr, SERVERPORT);


                ByteArrayOutputStream byteArrayOutputStream =
                        new ByteArrayOutputStream(1024);
                byte[] buffer = new byte[1024];

                int bytesRead;
                InputStream inputStream = socket.getInputStream();

                while ((bytesRead = inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                    message = byteArrayOutputStream.toString("UTF-8");
                    MainActivity.this.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            text.setText(message);
                        }
                    });

                }

            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }


    }


}

0 个答案:

没有答案