Reprint please specify: from Http://blog.csdn.net/soulscarrier
1. Open Two simulator:
Under Tools located in the command line to the SDK, enter Emulator-data foo to start two emulators.
2. Determine one of the servers as a server:
Need to have the Android emulator as a server to detect if two emulators are normal its command statement: ADB devices after you set up one of the servers. Its command-line statement is: The name of the telnet localhost + emulator, for example: Telnet localhost 5554: "5554" is the name of the emulator. After displaying "OK", proceed to the following statement: Redir add tcp:8192:8191
3. Execute the server-side and client code:
Server
public Class Server extends Activity {
public static final String ServerIP = "10.0.2.15";//This address is not actually used
public static final int serverport = 8191; Note that this is related to the configuration of the above redirection.
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
try {
ServerSocket serversocket = new ServerSocket (serverport);
while (true) {
Socket client = Serversocket.accept ();
System.out.println ("s:receiving...\n" +client.getinetaddress ());
Client.getinetaddress ();
}
}catch (Exception e) {
System.out.println ("S:error");
E.printstacktrace ();
}
}
}
Client
public class Client extends Activity {
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
try {
Socket socket = new Socket ("10.0.2.2", 8192);//Note this is also related to the configuration of the above redirection. And the address here must be 10.0.2.2.
} catch (Unknownhostexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Note: The androidmanifest.xml of two programs must add the following permissions:
About Android socket programming implemented in two emulators