public class Client extends AppCompatActivity {
public static final String TAG = Client.class.getSimpleName();
public static final int ServerPORT = 3000;
public static final String ServerIP = "10.146.166.86";
EditText message;
TextView mainView;
ClientThread clientThread;
Thread thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
message = (EditText)findViewById(R.id.message);
mainView = (TextView)findViewById(R.id.mainView);
}
public void updateMessage(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mainView.append(message + "\n");
}
});
}
public void onClick(View view) {
if (view.getId() == R.id.connectServer) {
mainView.setText("");
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
return;
}
if (view.getId() == R.id.sendMessage) {
Log.i(TAG, "Message sent from client");
clientThread.sendMessage(message.getText().toString());
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader input;
@Override
public void run() {
try {
InetAddress serverAdd = InetAddress.getByName(ServerIP);
socket = new Socket(serverAdd, ServerPORT);
while (!Thread.currentThread().isInterrupted()) {
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = input.readLine();
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
updateMessage(getTime() + " | Server : " + message);
break;
}
updateMessage(getTime() + " | Server : " + message);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
void sendMessage(String message) {
try {
if (null != socket) {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}
我写了一个简单的服务器 - 客户端TCP套接字连接,并一直在尝试连接主机和客户端。虽然我已经在另一个Thread(而不是mainThread)上运行了网络操作,但是当我尝试从客户端向我的服务器发送一个字符串时,它会抛出
android.os.NetworkOnMainThreadException.
对我来说似乎更奇怪,因为当我尝试切换主机和客户端设备时,现在我能够从客户端发送到我的服务器,但不能从服务器发送到客户端。然后,我得出结论,这应该归功于我的一个设备。一个运行Android 8,一个运行Android 6,似乎问题属于运行Android 8的问题。虽然我通过添加以下方法成功克服了这个问题:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
这对我来说似乎很奇怪,因为它的发生方式。它实际上取决于设备吗?
编辑:完整的错误消息。这很奇怪,因为它只发生在我的一个设备上。当我在设备之间切换角色时,它可以成功完成任务。
02-10 16:42:17.719 827-827/com.dev.kvuong2711.clienttcp I/Client: Message sent from client
02-10 16:42:17.720 827-827/com.dev.kvuong2711.clienttcp W/System.err: android.os.NetworkOnMainThreadException
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:108)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.io.BufferedWriter.flush(BufferedWriter.java:254)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.io.PrintWriter.newLine(PrintWriter.java:482)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.dev.kvuong2711.clienttcp.Client$ClientThread.sendMessage(Client.java:105)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.dev.kvuong2711.clienttcp.Client.onClick(Client.java:68)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.view.View.performClick(View.java:6256)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.view.View$PerformClick.run(View.java:24779)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.Handler.handleCallback(Handler.java:789)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:98)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.Looper.loop(Looper.java:180)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6950)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:835)
答案 0 :(得分:3)
sendMessage
中的代码未在另一个线程上运行,因为您将其放在另一个名为“Thread”的类中。当您调用run()
时,只有runnable的execute()
方法在另一个线程上运行。所以你要么必须在new Thread()
中调用sendMessage,要么将它放在某种线程安全变量或队列中,用run()
方法检查循环,然后发送。