Caused by: android.os.NetworkOnMainThreadException
You are trying to perform a potentially slow network operation on the main thread, this became a fatal exception in Android 3.0+. Simply move runTcpClient()
to a new Thread by using an AsyncTask or Loader.
Here is an example: How to fix android.os.NetworkOnMainThreadException?.
Try this:
class TcpClientTask extends AsyncTask<Void, Void, Void> {
private static final int TCP_SERVER_PORT = 1234;
private boolean error = false;
protected Void doInBackground(Void... arg0) {
try {
Socket s = new Socket("10.0.2.2", TCP_SERVER_PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//send output msg
String outMsg = "TCP connecting to " + TCP_SERVER_PORT + System.getProperty("line.separator");
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
//accept server response
String inMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpClient", "received: " + inMsg);
//close connection
s.close();
} catch (UnknownHostException e) {
error = true;
e.printStackTrace();
} catch (IOException e) {
error = true;
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
if(error) {
// Something bad happened
}
else {
// Success
}
}
}
To use it call: new TcpClientTask().execute();
I have 1 more question. String inMsg = in.readLine() + System.getProperty("line.separator");
which receives messages, how would I set it up to get it every 15ms or whatever is stable to keep receiving data.
I'm not certain what you are trying to do. But I noticed you only call readLine()
once, if you want to read more than one line, use a loop:
StringBuilder msg = new StringBuilder();
String line;
while((line = in.readLine()) != null) // Keep reading until the end of the file is reached
msg.append(in.readLine()).append(System.getProperty("line.separator"));
StringBuilders create less overhead when adding Strings together, simply use msg.toString()
when you want get the whole message.