In the course of a major project, a task for two mobile phone communication, but the simulator without IP support, so the Internet search solution, now describe a feasible solution as a summary report.
On the computer to open two simulator, two simulator IP address is the same, so to achieve communication, using the emulator IP address is not. But we can do this through port mapping, because the simulator actually has an analog address of 10.0.2.2, the address is equivalent to 127.0.0.1. So use in the ADB command: >adb–s emulator-5554 forwardtcp:8000 tcp:9000 can map the native port tcp/8000 to the emulator (5554) tcp/9000 port.
The server-side key code is:
Server = newserversocket (9000);
Socket = Server.accept ();
if (server!=null)
{
New Thread (new Runnable () {
Public void run () {
Try {
Socket =server.accept ();
Catch(IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
while (true) {
Try {
Receivemsg ();
Catch(IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
). Start ();
}
private void Receivemsg () throwsIOException {
reader = new bufferedreader (new InputStreamReader (
Socket.getinputstream ()));
Stringtxt = Reader.readline ();
Tv.settext (TXT);
}
Client-critical code is:
Try {
Socket = New socket ("10.0.2.2", 8000);
Catch(Unknownhostexception E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
Catch(IOException E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
}
Button.setonclicklistener (new Onclicklistener () {
Public void OnClick (View v) {
Stringtxt = Et.gettext (). toString ();
if (txt!= "" && txt!= null) {
Try {
sendmsg (TXT);
Catch(IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}}
}
});
Private PrintWriter getwriter (Socketsocket) throws IOException {
Outputstreamsocketout = Socket.getoutputstream ();
return New PrintWriter (Socketout, true);
}
private void Sendmsg (String Msg) throws IOException {
writer = new bufferedwriter (new OutputStreamWriter (
Socket.getoutputstream ()));
Writer.write (MSG);
Writer.flush ();
}
The implementation effect is as shown in the figure:
Implementation Principle Analysis: The simulator (5556) is connected to the 10.0.2.2:8000, which is equivalent to the 127.0.0.1:8000 of the local computer (PC), and is mapped to 9000 ports of the simulator (5554) due to the port mapping of the 8000 port of native IP. Therefore, a connection request from the emulator (5556) is sent to the emulator (5554). The network communication function between two simulators is realized.
This method is useful for native debugging.