android socket 编程——两个模拟器间的通信(同一台 PC)
1、首先启动两个 emulator,一个作为服务器,一个做为客端,在作为服务器的 emulator 中做适当配置。
emulator 的创建就不说了,自己参考相关资料。
执行 adb devices 可以看到两个设备的是否启动好,如下
List of devices attached
emulator-5554 device
emulator-5556 device
这里将 emulator-5554 作为服务器,将 emulator-5556 作为客户端。
在主机终端(既运行 cmd)下执行: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、分别编写服务器端程序和客户端程序
这里示意,所以程序很简单。
SocketServer 与SocketClient 工程
注意:两个程序的 AndroidManifest.xml 都必须加上下面这个权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
3、测试是否连接成功。
打开新的终端(运行 cmd),进入 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
说明连接成功。
接下来就可以做相关的数据传输动作了。
- 1
- 2
- 3
- 4
前往页