android.os.NetworkOnMainThreadException但我的类扩展了Thread

时间:2017-01-02 22:29:51

标签: java android multithreading sockets nullpointerexception

我有一个扩展Thread的客户端类来启动套接字编程 我的班级代码

class MyClientMessages extends Thread {
        Socket socket;
        int PORT = 5002;
        DataInputStream din;
        DataOutputStream dout;
        public MyClientMessages(String IP) {
            try {
                System.out.println("IP = ======= " + IP + " TYPE = " + TYPE);
                //*********** crash here ***************
                socket = new Socket(IP,PORT); // *********** it crash here *************
                din = new DataInputStream(socket.getInputStream());
                dout = new DataOutputStream(socket.getOutputStream());
                this.start();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run() {
            while (true) {
                byte[] data = new byte[1024];
                int size = 0;
                try {
                    while ((size = din.read(data)) > 0) {
                        final String str = new String(data,"UTF8");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                TextView textView = new TextView(ServerChat.this);
                                textView.setTextSize(15);
                                textView.setText(str);
                                linearLayout.addView(textView);
                            }
                        });
                    }
                }catch (IOException e) {
                    e.printStackTrace();
                    try {
                        dout.close();
                        din.close();
                        socket.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }

        public void WriteToSocket(byte[] arr,int size) {
            try {
                dout.write(arr,0,size);
                dout.flush();
            }catch (IOException e) {
                e.printStackTrace();
                try {
                    dout.close();
                    din.close();
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

我在我的活动类中创建了这个类。我的服务器活动类中有另一个类,它扩展了线程并且工作正常。为什么这个客户端类崩溃并给我这个错误?
我在onCreate()函数中如何使用它:

if (TYPE == 1) {
    serverMessages = new MyServerMessages(5002);
    Toast.makeText(this,"Room Started Wait clients To Join",Toast.LENGTH_LONG).show();
}
else {
    clientMessages = new MyClientMessages(deConvert(mycode)); // crash here
    Toast.makeText(this,"Connect To Room",Toast.LENGTH_LONG).show();
}

1 个答案:

答案 0 :(得分:2)

  

为什么这个客户端类崩溃并给我这个错误?

因为您正在创建Socket并在构造函数中打开它。将该逻辑移至run()