/* this application creates a socket connection to a remote server at port 80 and then sends an HTTP request to retrieve a web page */ import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*; public class SocketTest extends MIDlet { // define a StreamConnection to allow two direction comm. private StreamConnection SC = null; // define OutputStream to send request private OutputStream OS = null; private DataOutputStream DOS = null; // Define InputStream to receive responses from Web server private InputStream IS = null; private DataInputStream DIS = null; // Define the connection string private String connectStr = "socket://:127.0,0.1:80"; // Create a string buffer to store the web page content private StringBuffer content; // Create the User interface private Display display = null; // initial value null private Form fmMain; private StringItem result; // Constructor public SocketTest() { // Initialise UI content = new StringBuffer(); display = Display.getDisplay(this); fmMain = new Form("Page Content: "); // new screen to display result of //content retrieval } // StartApp public void startApp(){ // Establish a socket connection try { SC = (StreamConnection) Connector.open(connectStr); // Create DataOutputStream on top of the socket connection OS = SC.openOutputStream(); DOS = new DataOutputStream(OS); // send HTTP request DOS.writeChars("GET http://www.brunel.ac.uk/~emstaam/home.htm \n"); DOS.flush(); // create DataInputStream on top of the socket connection IS = SC.openInputStream(); DIS = new DataInputStream(IS); // retrieve the content of requested page from web server int inputChar; // check while data is valid show on display while((inputChar = DIS.read()) != -1){ content.append((char) inputChar); } // display the page content on the screen result = new StringItem(null, content.toString()); // char to str conversion fmMain.append(result); display.setCurrent(fmMain); } catch (IOException e){ System.err.println("Exception: " + e); } finally { // release resources and close socket try { if (DOS != null) DIS.close(); } catch (Exception ignored) {} try { if (DOS != null) DOS.close(); } catch (Exception ignored) {} try { if (OS != null) OS.close(); } catch (Exception ignored) {} try { if (IS != null) IS.close(); } catch (Exception ignored) {} try { if (SC != null) SC.close(); } catch(Exception ignored){ } } } public void pauseApp(){ } public void destroyApp(boolean unconditional){ } }