android socket编程——两个模拟器间的通信(一台PC)

1、首先启动两个emulator,一个作为服务器,一个做为客端,在作为服务器的emulator中做适当配置。
emulator的创建就不说了,自己参考相关资料。
执行 adb devices 可以看到两个设备的是否启动好,如下
List of devices attached 
emulator-5554    device
emulator-5556    device
这里将emulator-5554 作为服务器,将emulator-5556 作为客户端。
在主机终端下执行: telnet localhost 5554  连上服务器emulator-5554
显示信息如下:
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Android Console: type 'help' for a list of commands
OK

继续执行: redir add tcp:8192:8191  作下重定向
2、分别编写服务器端程序和客户端程序
这里示意,所以程序很简单。
server:
public class server extends Activity {
    /** Called when the activity is first created. */
    public static final String SERVERIP = "10.0.2.15";//这个地址其实没有用到
    public static final int SERVERPORT = 8191;   //注意这里和上面重定向的配置是有关系的。
    @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 {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        
        try {
            Socket socket = new Socket("10.0.2.2", 8192); //注意这里也是和上面重定向的配置是有关系的。而且这里的地址必须是10.0.2.2
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
}
注意:两个程序的AndroidManifest.xml都必须加上下面这个权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

3、测试是否连接成功。
打开新的终端,进入emulator-5554 的console中,即执行 adb -s emulator-5554 shell
接着logcat
将server端程序编译运行在emulator-5554上
将client端程序编译运行在emulator-5556上
可以看到log的信息:在没有启动client时,一直等待连接,在启动client以后,log中打出
I/System.out(  382): S: Receiving...
I/System.out(  382): /10.0.2.2
说明连接成功。
接下来就可以做相关的数据传输动作了。

参考资料:
http://developer.android.com/guide/developing/devices/emulator.html#connecting

你可能感兴趣的:(android socket编程——两个模拟器间的通信(一台PC))