Antons Channel
Antons Channel

Reputation: 23

Writing data to OutputStream without closing with CLDC

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");
    }

Upvotes: 0

Views: 318

Answers (1)

0x777C
0x777C

Reputation: 1047

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

Upvotes: 0

Related Questions