codenameone sequential socket write/read

Viewed 132

I'm trying to implement a SMTP protocol in my app, but I have a problem doing more than 1 write/read on a InputStream/OutputStream using codenameone SocketConnection.
This is what I have so far:

Socket.connect("<google ip>",25,new SocketConnection(){
    @Override
    public void connectionError [...]

    @Override
    public void connectionEstablished(InputStream is, OutputStream os){
       try{
          BufferedInputStream in = new BufferedInputStream(is);
          BufferedOutputStream out = new BufferedOutputStream(os);
          byte[] response = new byte[1024];
          String z;
          int size;

          out.write( ("HELO mydomain.me").getBytes() );
          out.flush();
          size = in.read(response);
          //in.mark(size);
          //in.reset();
          z = new String(response, 0 ,size);
          System.out.println(z);
          response = new byte[1024];

          out.write( ("MAIL FROM: <myaddress@bubu.me>").getBytes() );
          out.flush();
          System.out.println("I get here!");
          size = in.read(response);
          System.out.println("I NEVER get here!");
          z = new String(response, 0 ,size);
          System.out.println(z);

          [... rest of SMTP that I never reach ...]

       }catch(IOException ex){
          System.out.println("I don't even get connection errors");
       }
    }
}

This is the output I get:

220 mx.google.com ESMTP [...] -gsmtp

i get here!

And the program get stuck here.

Which means the "HELO ..." and its response works fine, but then it get stuck trying to read a second time from the BufferedInputStream.

I have tried to switch from BufferedInputStream to InputStream, all combination of in.mark(size); , in.reset() , reading only a fixed amount of bytes (in.read(response, 0 , 200)), but I did not manage to make it work.

What could I do to fix this?

2 Answers

I would start by removing the buffering from both streams, at least for now, because (a) that would narrow the list of suspects, (b) it's an optimization that may not be needed and complicates the example code, (c) it's possible that SocketConnection itself buffers the streams behind the scenes.

Another thing you could check: The examples of SMTP I have seen do not have a space after MAIL FROM:.

By the way, there are several open source Java libraries for SMTP you might be able to use instead of building your own.

You don't need the buffered streams as streams in Codename One are already buffered by default.

I don't really recall the SMTP protocol but check that your server supports this and try ehelo, adding crlf etc. Being stuck on read just means the server is still waiting on input from you.

Related