i am using an example to learn the use of sockets in android. i'm kind of new to this and I'm using a book to learn. I can't really figure out whats the problem, as the example is literally copied from the book, except for the IP, which is my computer's. the android app keeps throwing this error:
error:android.os.NetworkOnMainThreadException
I post the code:
as some words are in spanish i will translate them for you, just in case it makes it easier to understand:
PUERTO-->port,ENTRADA-->input,SALIDA-->output,ENVIANDO-->sending,HOLA MUNDO-->hello world,RECIBIENDO-->receiving,DATOS-->data,CLIENTE-->client
ANDROID CLIENT
package com.jacho981.clienteecho;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ClienteECHO extends Activity {
private TextView output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cliente_echo);
output = (TextView) findViewById(R.id.TextView01);
ejecutaCliente();
}
private void ejecutaCliente() {
// String ip = "158.42.146.127";
String ip = "192.168.1.3";
int puerto = 7;
log(" socket " + ip + " " + puerto);
try {
Socket sk = new Socket(ip, puerto);
BufferedReader entrada = new BufferedReader(new InputStreamReader(
sk.getInputStream()));
PrintWriter salida = new PrintWriter(new OutputStreamWriter(
sk.getOutputStream()), true);
log("enviando...");
salida.println("Hola Mundo");
log("recibiendo..." + entrada.readLine());
sk.close();
} catch (Exception e) {
log("error: " + e.toString());
}
}
private void log(String string) {
output.append(string + "\n");
}
}
JAVA SERVER
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServidorECHO {
public static void main(String args[]) {
try {
ServerSocket sk = new ServerSocket(7);
while (true) {
Socket cliente = sk.accept();
BufferedReader entrada = new BufferedReader(
new InputStreamReader(cliente.getInputStream()));
PrintWriter salida = new PrintWriter(new OutputStreamWriter(
cliente.getOutputStream()), true);
String datos = entrada.readLine();
salida.println(datos);
cliente.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
}