0

I have a small J2ME app that should send some bytes to a socket and read response. However, when I close OutputStrean, the socket closes too, and I can't read response. I thought I could try OutputStream.flush();, but it does nothing. Here is my readAll() method that should read data from OutputStream:

public final static String readAll(InputStream d) throws IOException {
        ByteArrayOutputStream res = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int length;
        while ((length = d.read(bytes)) != -1){
            res.write(bytes, 0, length);
        }
        return new String(res.toByteArray(), "UTF-8");
    }
  • Do not close OutputStrean before reading the response. – Telmo Pimentel Mota Oct 01 '19 at 11:33
  • Well, response is generated using data, that is transfered by the client; but without closing that OutputStream data won't be send, so server won't be able to send response. If I close OutputStream, the server handles the input fine, but because the client SocketConnection is closed, it can't write data to its InputStream. – Antons Channel Oct 01 '19 at 14:26

1 Answers1

0

You'll typically want to have a thread running in the background that handles actually sending and receiving data.

The data that is received should provide some way of determining when that particular chunk of data terminates. For example, the server might send back:
(long)length+(byte[])data
So from the stream you would read in take 8 bytes + whatever the length is, then you would use that data to construct an object that represents that message and your other thread would read in that data to decide what data it wants to send out.

In order to send data out you would effectively do the reverse, with a separate thread consuming objects that represent messages to be sent.

These are called message queues and you can read more about them here: https://en.wikipedia.org/wiki/Message_queue

0x777C
  • 993
  • 7
  • 21