Search code examples
androidmultithreadingsocketstcp

Multiple write and read over socket


I need an app to connect a board by Wifi. There are four fragments that by clicking everyone I have to write arraybyte or one byte and then read arrayByte. At first time, I just read arrayBte without writing and it is work perfect, but by clicking other fragments, I always get null. This is my code:

public class CommsThread extends Thread {
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;

public CommsThread() {
    try {
        socket = new Socket(Const.ip, Const.port);
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStream tmpIn = null;
    OutputStream tmpOut = null;
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();

    } catch (IOException e) {
        Log.d("SocketChat", e.getLocalizedMessage());
    }
    inputStream = tmpIn;
    outputStream = tmpOut;
}

public void run() {
    while (true) {
        try {
            byte[] data = new byte[1];
            inputStream.read(data);
            readData.add(data[0]);
        } catch (IOException e) {
        }
    }
}

 public void write(ArrayList<Byte> bytes) {
        ArrayList list = new ArrayList();
        list.add((byte)0xFE);
    for (byte b: bytes)
    {
        if(b >= 0xFD)
        {
            list.add((byte)0xFD);
            list.add((byte)(b - 0xFD));
        }
        else
            list.add(b);
    }
    list.add((byte)0xFF);
    byte[] listBytes = new byte[list.size()];
    for (int i = 0; i < list.size(); i++) {
        listBytes[i] = (byte)list.get(i);
    }
    try {
        outputStream.write(listBytes);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

I Used this code within an asynckTask class:

Const.commsThread = new CommsThread();
                Const.commsThread.start();

by clicking a fragment, I call write function:

//for example
     sendToServer("5");

 public static class WriteToServerTask extends AsyncTask<byte[], Void, Void> {
    protected Void doInBackground(byte[]... data) {
        ArrayList list = new ArrayList();
        list.add((byte)0x05);

        Const.commsThread.write(list);
        return null;
    }
}

public static void sendToServer(String message) {
    byte[] theByteArray = message.getBytes();
    new WriteToServerTask().execute(theByteArray);
}

I don't get error, but it never exit to while to execute write function. Thanks in advance.


Solution

  • response2 is most likely null because inputStream.read(Const.data2) is returning -1. This will be the case if, for example, the socket has been closed by the peer (docs).

    You should add some additional handling for the -1 case. Also consider adding some logging to help you understand what is going on in the program.

    run() will be executed asynchronously shortly after you call Const.commThread.start().