我正在编写简单的软件,PC 是套接字服务器,android 连接到它,然后无论我在 PC 上的键盘上写什么,android 都会得到它并简单地记录。
安卓代码:包com.example.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("192.168.2.3", 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
Log.e("j", "Don't know about host: JANIPC.");
System.exit(1);
} catch (IOException e) {
Log.e("j", "Can't connect to Jani-PC");
System.exit(1);
}
try {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
//out.println(userInput);
Log.e("j", "echo: " + in.readLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是我的 PC Java 代码:
package jani.study.socketserver;
import java.io.*;
import java.net.*;
/**
*
* @author Jani
*/
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
System.in));
String inputLine;
System.out.println("Connected!");
/*while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
}*/
Thread.sleep(1000);
out.println("1");
Thread.sleep(1000);
out.println("2");
Thread.sleep(1000);
out.println("3");
Thread.sleep(1000);
out.println("4");
Thread.sleep(1000);
out.println("5");
Thread.sleep(1000);
out.println("6");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
在 Android 调试器中,我只得到每秒一次的请求,我的意思是,我只得到: echo: 2 echo: 4 echo: 6
我究竟做错了什么?请帮忙