我有一个扩展 Thread 的客户端类来启动套接字编程
我的类(class)代码
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();
}
}
}
}
我在我的 Activity 课中开设了这门课。我的服务器 Activity 类中有另一个类,它扩展了线程并且工作正常。为什么这个客户端类会崩溃并给出此错误?
这是我在 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();
}
最佳答案
why this client class crash and give me this error ?
因为您正在创建一个 Socket
并在构造函数中打开它。将该逻辑移至 run()
中。
关于java - android.os.NetworkOnMainThreadException 但我的类扩展了 Thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41434030/