Wednesday, April 27, 2011

Socket connection


/*
J2ME: The Complete Reference

James Keogh

Publisher: McGraw-Hill

ISBN 0072227109

*/
// jad file (Please verify the jar size first)
/*
MIDlet-Name: socketconnection
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: socketconnection.jar
MIDlet-1: socketconnection, , socketconnection
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100

*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
public class socketconnection extends MIDlet implements CommandListener {
private Command exit, start;
private Display display;
private Form form;
public socketconnection ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
start = new Command("Start", Command.EXIT, 1);
form = new Form("Read Write Socket");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp() throws MIDletStateChangeException
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
else if (command == start)
{
try
{
StreamConnection connection = (StreamConnection) Connector.open("socket://www.myserver.com:80");
PrintStream output =
new PrintStream(connection.openOutputStream() );
output.println( "GET /my.html HTTP/0.9\n\n" );
output.flush();
InputStream in = connection.openInputStream();
int ch;
while( ( ch = in.read() ) != -1 )
{
System.out.print( (char) ch );
}
in.close();
output.close();
connection.close();
}
catch( ConnectionNotFoundException error )
{
Alert alert = new Alert(
"Error", "Cannot access socket.", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
catch( IOException error )
{
Alert alert = new Alert("Error", error.toString(), null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
}
}
}


No comments:

Post a Comment

Search This Blog

Total Pageviews