I’ve write a server-client model android program. My pc acts as server and AVD acts as the client. I’m using 10.0.2.2 as the server’s address to connect, but the server side recieves nothing. My server works fine when the client is an usual java program. Problem occurs when the client is an Android emulator. I’ve been working on the problem for a really long time but I still have no solution. Hope someone could help me, thanks!
My code:
server:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException{
ServerSocket server = new ServerSocket(6002);
while(true){
Socket client = server.accept();
BufferedReader in= new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println(in.readLine());
}
}
}
client:
public class modules extends Activity {
private ListView myListView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.modules);
myListView = (ListView)findViewById(R.id.listView1);
Intent intent = getIntent();
Bundle b = intent.getExtras();
String semester = b.getString("semester");
String subject = b.getString("subject");
try {
Socket socket = new Socket("10.0.2.2",6002);
PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
String s1 = "SEME" + semester;
out.println(s1);
out.flush();
String s2 = "SUBJ" + subject;
out.println(s2);
out.flush();
socket.close();
} catch(UnknowHostException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}
In logcat there are Errors like:
android.os.NetworkOnMainThreadException;
and also errors with Strict Mode:
07-22 14:24:24.892: E/AndroidRuntime(759): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099).
I have added the user-permission in the manifest xml file, so the problem must be something else.
Look at what the error says: NetworkOnMainThreadException. It means that you should not do network operations on Android’s main thread because if your request happens to delay for a while responsiveness of the device will be blocked until that request is done.
In order to use the Socket client on android you should give a look to AsyncTask, Thread or Service maybe. I would recommend you to use AsyncTask which is pretty straightforward. The code you have in your onCreate() method should be put in another class that extends AsyncTask this way:
For more information check the docs for AsyncTask or browse the web/stackoverflow for complete examples!
Hope this helps… bye.