情形一:
Android_Server:
final int SERVER_PORT = 12345;
private void startServer()
{
try
{
Log.e("s: connecting...", "");
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
while (true)
{
Socket client = serverSocket.accept();
Log.e("s: receiving...", "jjjjjj");
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
Log.e("s: received:'" , "%%%%%%" + str);
}
catch (Exception e)
{
Log.e("s: error", "");
e.printStackTrace();
}
finally
{
client.close();
Log.e("s:done", "");
}
Thread.sleep(3000);
}
}
catch (Exception e)
{
Log.e("s:error", "");
e.printStackTrace();
}
}
PC_Client:
try
{
Runtime.getRuntime().exec("adb forward tcp:12581 tcp:12345");
}
catch (IOException e3)
{
e3.printStackTrace();
}
Socket socket = null;
try
{
InetAddress serverAddr = null;
serverAddr = InetAddress.getByName("127.0.0.1");
System.out.println("TCP 1111" + "C: Connecting...");
socket = new Socket(serverAddr, 12581);//此处的12581是PC开放的端口,已重定向到Device的12345端口
String message = "AndroidRes,Where is my Pig (Android)?";
System.out.println("TCP 2222" + "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(message);
}
catch (UnknownHostException e1)
{
System.out.println("TCP 3333" + "ERROR:" + e1.toString());
}
catch (IOException e2)
{
System.out.println("TCP 4444" + "ERROR:" + e2.toString());
}
finally
{
try
{
if (socket != null)
{
socket.close();
}
}
catch (IOException e)
{
System.out.println("TCP 5555" + "ERROR:" + e.toString());
}
}
}
Android_Server与PC_Client连接成功~
情形二:
PC_Server:
try
{
Runtime.getRuntime().exec("adb forward tcp:12555 tcp:12345");
System.out.println("s: connecting...");
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);