I have used AsyncTask to establish the server socket connection, then accept the client connection, finally need to update the GUI each time the client send data to server.
But what actually happen that when the client send data the GUI wasn't updated, if the client disconnect the connection then the GUI will update. this happen when the client make three connection and then disconnection then the GUI will be updated. but after that the GUI won't be updated then I can't see the data which the client sent to the server. How to solve this problem.
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);
} }