2017-01-02 61 views
0

我有继承Thread开始socket编程
我的类代码
android.os.NetworkOnMainThreadException但我的类继承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(); 
} 

回答

2

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

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

+0

谢谢你的作品很棒:D –