这个在真机上是可以做的
http://www.360doc.com/content/11/0610/17/128678_126054438.shtml
参照这篇文章:有几点注意,按照这么做
主要就是用adb forward重定向端口,将本机地址127.0.0.1的端口重定向
1、有时出现refuse connect (原因不明,重启手机试试)
2、要指定编码
3、adb 的环境变量
4、注意权限
真机做是没问题。。。。
服务器-------------------------------------------------------------------------------------------
try {
Runtime.getRuntime().exec("cmd /c adb shell am broadcast -a NotifyServiceStop");
Runtime.getRuntime().exec("cmd /c adb forward tcp:12580 tcp:10086");
Runtime.getRuntime().exec("cmd /c adb shell am broadcast -a NotifyServiceStart");
// 不加这个等待,会报connect reset的异常在服务器端
Thread.slee(3000);
} catch (IOException e3) {
e3.printStackTrace();
}
Socket socket = null;
try {
System.out.println("TCP 1111" + "C: Connecting...");
socket = new Socket("127.0.0.1", 12580);
String str = "hi,wufenglong";
System.out.println("TCP 221122" + "C:RECEIVE");
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
BufferedInputStream in = new BufferedInputStream(socket
.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
out.write("测试".getBytes("utf-8"));
out.flush();
out.write("测试".getBytes("utf-8"));
out.flush();
out.close();
System.out.println("reader " + br.readLine());
} catch(Exception e) {
e.printStackTrace();
}
android -------------------------------------------------------------------------------------------------
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
public void run() {
try {
ServerSocket server = new ServerSocket(10086);
Log.d("tag", "server");
Socket socket = null;
while((socket = server.accept()) != null) {
Log.d("tag", "accept");
InputStream is = socket.getInputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
byte[] bytes = new byte[1024];
int count = is.read(bytes, 0, 1024);
Log.d("tag", "count " + new String(bytes,0,count,"utf-8"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}