我使用AsyncTask建立服务器套接字连接,然后接受客户端连接,最后每次客户端向服务器发送数据时都需要更新GUI。
但实际发生的情况是,当客户端发送数据时GUI未更新,如果客户端断开连接,则GUI将更新。这种情况发生在客户端进行三次连接然后断开连接时,GUI将会更新。但之后GUI不会被更新,那么我就看不到客户端发送给服务器的数据了。如何解决这个问题。
public class ServerSocket_test extends Activity {
private TextView textView;
private EditText editIP;
private EditText editMessage;
private Socket socketClient=null;
private PrintWriter printWriterClient=null;
public static final int LISTEN_PORT = 6000;
private class TaskServerSocket extends AsyncTask<Void, Void, Void> {
@SuppressLint("NewApi")
@Override
protected Void doInBackground(Void... v) {
try {
ServerSocket serverSocket = new ServerSocket(LISTEN_PORT);
while (true) {
socketClient = serverSocket.accept();
TaskRead taskRead = new TaskRead();
taskRead.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, socketClient);
}
} catch (IOException ex) {
Log.e("SocketsChat", ex.getLocalizedMessage());
}
return null;
}
}
private class TaskRead extends AsyncTask<Socket,String,Void> {
String in="";
@Override
protected Void doInBackground(Socket... socketClient) {
String s;
try {
BufferedReader input = new BufferedReader(
new InputStreamReader(socketClient[0].getInputStream()));
while (true){ //(socketClient[0].isConnected()) {
while ((s=input.readLine())!=null) {
publishProgress(s, socketClient[0].getInetAddress().toString());
}
}
} catch (IOException exc) {
Log.d("SocketChat", exc.getLocalizedMessage());
}
return null;
}
@Override
protected void onProgressUpdate(String... strings) {
textView.append(strings[1]+": "+strings[0]+"\n");
in=in+strings;
}
@Override
protected void onPostExecute(Void result){
textView.append(in);
}
}
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_socket_test);
textView = (TextView) findViewById(R.id.textView1);
TaskServerSocket taskServerSocket = new TaskServerSocket();
taskServerSocket.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} }
答案 0 :(得分:0)
必须在UI(主)线程中启动AsyncTask。
在您的代码中,您在TaskServerSocket的doInBackground方法中启动TaskRead。 方法doInBackground不在UI(主)线程中。
请参阅文档:http://developer.android.com/reference/android/os/AsyncTask.html
“必须在UI线程上加载AsyncTask类”
另一点,在你的情况下,2 AsyncTasks很奇怪,似乎不必要。如果你合并两个AsyncTask,那就更好了。