我是开发Android的新手。我的应用程序是TCP服务器外的客户端。我需要使用Socket将文本数据从EditText发送到后台线程中的服务器。从服务器回答我需要添加到TextView。我看到很多例子,但没有看到我能理解的例子。所以我需要一个特别适合我的简单例子。对不起我的英语不好。 AsyncTask只用于一次性使用。我只需要Thread。据我所知,我需要:Thread(Runnable),Handler,Message,Looper ..但我不明白如何使用所有这些类。
ublic class ServerWork extends Thread{
public static final Character PREFIX = ###;
public static final Character SUFFIX = ###;
public static final int SERVERPORT = ###;
public static final String SERVER_IP = ###;
private Socket socket;
String response;
String inputStr;
public ServerWork(String inputStr){
this.inputStr = inputStr;
}
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
String str = PREFIX + inputStr + SUFFIX;
PrintWriter printOut = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
BufferedReader inputBuffer = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
printOut.println(str);
printOut.flush();
char buf[] = new char[ 1000 ];
int count = inputBuffer.read( buf );
response = new String( buf, 0, count );
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}