Search code examples
java-memidletmidp

MIDP 2.0 TCP Client


I am trying to develop a TCP client that runs on mobile devices using MIDP 2.0 and CLDC 1.1. I am trying some sample code, and I have the following problem:

I get a weird exception when I try to read the data back (From the MIDlet).

This is my code:

            //Wait for an incoming message
            firstByte = in.read();
            ByteArrayOutputStream textRecieved = new ByteArrayOutputStream();   //Will be used to hold the data
            if (firstByte >= 0 )
            {                    
                int messageSize = this.in.available();

                //Read the message
                while (messageSize > 0)
                {
                    byte[] buffer = new byte[messageSize];  
                    this.in.read(buffer);
                    textRecieved.write(buffer);
                    messageSize = this.in.available();   //Just in case the server sent the request in chunks.
                    System.out.println("Reading...");
                }
            }
            textRecieved.close();

This is the exception I get:

java.io.IOException: Unknown error 10053 during socket::read 
        at com.sun.midp.io.j2me.socket.Protocol.read0(), bci=0
        at com.sun.midp.io.j2me.socket.Protocol.nonBufferedRead(), bci=12
        at com.sun.midp.io.BufferedConnectionAdapter.readBytes(), bci=36
        at com.sun.midp.io.BaseInputStream.read(), bci=227
        at com.sun.midp.io.BufferedInputStream.fill(), bci=172
        at com.sun.midp.io.BufferedInputStream.read(), bci=16
        at hello.Client.run22222(Client.java:60)
        at hello.HelloMIDlet.startApp(HelloMIDlet.java:193)
        at javax.microedition.midlet.MIDletTunnelImpl.callStartApp(), bci=1
        at com.sun.midp.midlet.MIDletPeer.startApp(), bci=7
        at com.sun.midp.midlet.MIDletStateHandler.startSuite(), bci=269
        at com.sun.midp.main.AbstractMIDletSuiteLoader.startSuite(), bci=52
        at com.sun.midp.main.CldcMIDletSuiteLoader.startSuite(), bci=8
        at com.sun.midp.main.AbstractMIDletSuiteLoader.runMIDletSuite(), bci=161
        at com.sun.midp.main.AppIsolateMIDletSuiteLoader.main(), bci=26

The line that causes the exception is this:

firstByte = in.read();

I am reading on a separate thread. I experienced the same error when I sent requests and tried to read them using the same server. The server is a simple echo server, nothing complex.

P.S. I know that the way the code is written looks like C#, but it is Java, I find it easier to read and follow this way.

Thanks.


Solution

  • This example seems to be working: http://www.java-samples.com/j2me/socket-connection-free-j2me-sample-program.htm

    Could it be that the problem was that I was implementing the client as a class called by the midlet?