Search code examples
androidsocketsclientoutputstream

Message was send for first time, Why I can't send message again (Android Socket Programming)


I created socket programming class for client. Connection was made. Server send a message to client. Client can take messages from server. But client only an answer sends. Why? Is the outputstream wrong?

public class Message extends AsyncTask<byte[], Void, Void> {
        Socket s;
        public static byte[] recv;
    
    
        @Override
        protected Void doInBackground(byte[]... voids) {
            byte[] message = voids[0];
            try {
                s = new Socket(destIp, destPort);
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                dos.writeInt(message.length);
                dos.write(message);
                dos.flush();
                InputStream inFromServer = s.getInputStream();
                DataInputStream in = new DataInputStream(inFromServer);
    
                byte[] buffer = new byte[200];
                int read = 0;
                while ((read = in.read(buffer, 0, buffer.length)) != -1) {
    //                in.read(buffer);
                    recv = Arrays.copyOf(buffer, read);
                    Context context = getContext();
                    Intent intentManager = new Intent(context, ManagerService.class);
                    context.startService(intentManager);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

Solution

  • I fixed this in the part I start asynctask

    new MessageReceive().execute(sendData);
    

    to

    new MessageReceive().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,sendData);