Persistent connection

I am trying to establish a permanent connection between a MIDLet in J2ME and a J2SE Servlet.

I have tried different possibilities whitout success. The first thing I have tried is setting the Connection property to Keep-alive. I have also tried increasing the content-length property in the server by two (I have read in an article that sometimes there are some problems between a MIDlet and a Servlet because of the content-length).

If I try to write just one time there is no problem, but when writting for a second time I receive an Exception in the MIDlet as follows:

java.io.IOException: connection already open

at com.sun.midp.io.j2me.http.Protocol.setRequestProperty(+18)

at com.sun.midp.io.j2me.http.Protocol.flush(+30)

at com.sun.midp.io.BaseOutputStream.flush(+11)

at java.io.DataOutputStream.flush(+7)

at Pru.commandAction(+104)

at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(+152)

at com.sun.kvem.midp.lcdui.EmulEventHandler$EventLoop.run(+459)

I am not sure if the MIDP specification does not support persistent connectios between MIDlets and servlets. I would appreciate if you could help me with it or if you have an example of communications using persistent connecitions between MIDlets and Servlets. The versions I am using are:

J2ME Wireless Toolkit 1.0.4_01

Apache Tomcat 4.0.3 (servlet engine)

Implementation of the Servlet 2.3

Looking forward to hearing from you

William

I enclose a file with the midlet and servlet, and the different ways I have used to read and write.

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

import javax.microedition.io.*;

import java.io.*;

public class Pru extends MIDlet implements CommandListener{

private Display _display;

private Command _send = new Command("Send", Command.OK,2);

private Form _form;

HttpConnection conn = null;

DataOutputStream dout = null;

InputStream din = null;

public Pru(){

}

public void startApp() throws MIDletStateChangeException{

try{

conn = (HttpConnection)Connector.open("http://xxx/servlet/Prueba"); //Conexion abierta

}

catch(IOException e){

}

_display=Display.getDisplay(this);

_form=new Form("Registration");

_form.addCommand(_send);

_form.setCommandListener(this);

_display.setCurrent(_form);

}

public void pauseApp(){

}

public void destroyApp(boolean unconditional){

_form=null;

notifyDestroyed();

try{

dout.close();

din.close();

conn.close();

}

catch(IOException e){

}

}

public void commandAction(Command c, Displayable s){

System.out.println("Entro en command, dout vale: " + dout + "\n");

if(c == _send){

String cadena = new String("Holapp");

String leido = new String();

try{

dout = conn.openDataOutputStream();

if(dout == null){

conn.setRequestMethod(HttpConnection.POST);

/********I have tried to set different properties each time but without a satisfactory solution********************/

/*

conn.setRequestProperty( "User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" );

conn.setRequestProperty( "Content-Language", "en-US" );

conn.setRequestProperty( "Accept", "application/octet-stream" );

conn.setRequestProperty( "Content-Accept", "application/octet-stream" );

conn.setRequestProperty("Protocol", "HTTP/1.1");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Host", "la.it.uc3m.es");

conn.setRequestProperty("URL", "http://la.it.uc3m.es/examples/servlet/Prueba");

conn.setRequestProperty("Content-Type", "");

conn.setRequestProperty( "Content-Length","4");

*/

}

// else{

//try{

//conn.setRequestMethod(HttpConnection.POST);

/*

System.out.println( " Content-Accept es : " + conn.getRequestProperty("Content-Accept") + "\n");

System.out.println( "Content-Length es : " + conn.getRequestProperty("Content-Length") + "\n");

System.out.println( " User es : " + conn.getRequestProperty("User-Agent") + "\n");

System.out.println( "Language es : " + conn.getRequestProperty("Content-Language") + "\n");

System.out.println( "Protocolo es : " + conn.getProtocol() + "\n");

System.out.println( "el metodo es : " + conn.getRequestMethod() + "\n");

*/

/*}catch(IOException e){

System.out.println("El error es :" + e.getMessage());

e.printStackTrace();

}*/

// }

byte[] datos = cadena.getBytes();

// conn.setRequestProperty( "Content-Length",String.valueOf(cadena.length()));

dout.write(datos);

dout.flush();

System.out.println( "la longitud es : " + conn.getHeaderField("Content-Length") + "\n");

if(din == null){

din = conn.openInputStream();

}

StringBuffer sb = new StringBuffer("");

int cad = 0;

long len = conn.getLength();

for (int ccnt=0; ccnt < len; ccnt++){

cad = din.read();

sb.append((char)cad);

}

//******************* ANOTHER WAY TO READ***************************

/*StringBuffer sb = new StringBuffer("");

int ch = 0;

while ((ch = din.read()) != -1) {

sb.append((char)ch);

}

*/

System.out.println("Leido: " + sb.toString() + "\n");

System.out.println(" el codigo de respuesta " +conn.getResponseMessage()+"\n");

//I try to read again in order to check the state of the conexion (close, keep-alive)

dout.write(datos);

dout.flush();

}

catch(IOException e){

System.out.println("Excepcion capturada: " + e.getMessage() + "\n");

e.printStackTrace();

}

}//if

}//commandAction

}

/************************************************************************************

SERVLET

*********************************************************************************/

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Prueba extends HttpServlet{

int contador=0;

public void init(ServletConfig configuracion) throws ServletException{

super.init(configuracion);

int resultado=-1;

System.out.println("Servlet Pru arrancado...\n");

System.out.println("SE ha visitado..."+contador+"\n");

}

public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {

String text = new String();

System.out.println("1 Estoy en post ...\n");

contador++;

System.out.println("SE ha visitado..."+contador+"\n");

try{

InputStream din = request.getInputStream();

int lon=request.getContentLength()+2;

String s="";

System.out.println("despues din null el tama駉 recibido es "+lon+"\n");

for (int cont=0;cont<long ;cont++ ){

text = text + (char)din.read();

}

System.out.println( " El metodo es : " + request.getMethod() + "\n");

System.out.println( "URL es : " + request.getRequestURL() + "\n");

System.out.println( " User es : " + request.getHeader("User-Agent") + "\n");

System.out.println( "Language es : " + request.getHeader("Content-Language") + "\n");

System.out.println( " Accept es : " + request.getHeader("Accept") + "\n");

System.out.println( "Content-Accept es : " + request.getHeader("Content-Accept") + "\n");

System.out.println( "Content-Length es : " + request.getHeader("Content-Length") + "\n");

System.out.println( "la conexion es : " + request.getHeader("Connection") + "\n");

System.out.println( "Protocolo es : " + request.getProtocol() + "\n");

//**********************ANOTHER WAY TO READ***********************************

/* if(lon >2 ){

System.out.println("he entrado en el if \n");

BufferedReader reader=request.getReader();

char[] buffer=new char[lon];

System.out.println(" he llamado a la funcion getReader");

int i =reader.read(buffer,0,buffer.length);

System.out.println(" reader.read");

s=new String(buffer);

s=s.substring(0,s.length()-2);

System.out.println(" los datos leidos son :"+ s);

}

*/

//******************* ANOTHER WAY TO READ***************************

/*StringBuffer sb = new StringBuffer("");

int ch = 0;

while ((ch = din.read()) != -1) {

sb.append((char)ch);

}

*/

System.out.println("Hemos leido: " + text + "\n");

String cadena="echo"+text;

System.out.println("Mando: " + cadena + "\n");

// response.setContentType("application/octet-stream");

//response.setStatus(response.SC_OK);

response.setContentLength(cadena.length());

OutputStream dout = response.getOutputStream();

byte[] datos = cadena.getBytes();

dout.write(datos);

System.out.println("Salido de post\n");

}

catch(IOException e){

System.out.println("Excepcion en servlet: " + e.getMessage() + "\n");

}

}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{

doPost(request,response);

}

[9541 byte] By [gdandino] at [2007-9-27 21:06:55]
# 1

I also have been surfing the web to find out how to implement

an applet-to-servlet communication link over a persistent http connection.

There is a working implementation available for download at

http://www.ustobe.com/

After clicking on the 'news' item in the menu, there are links

available to download HttpKeepalive.java, with javadoc explaining

how to use this class.

Mike

mikethomas316 at 2007-7-7 2:49:46 > top of Java-index,Java Mobility Forums,Java ME Technologies...
# 2
HI, i could not find this example on the mentioned website....HttpKeepalive.java..does any body know about it or has this exmaple code.... does any body know how to establish persistent http pr https connections..please helpAkhil
akhilnagpal at 2007-7-7 2:49:46 > top of Java-index,Java Mobility Forums,Java ME Technologies...