PatchyMIDlet.java Source code

Java tutorial

Introduction

Here is the source code for PatchyMIDlet.java

Source

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;

import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;

public class PatchyMIDlet extends MIDlet implements CommandListener, Runnable {
    private Display mDisplay;

    private Form mForm = new Form("PatchyMIDlet");

    private ServerSocketConnection mServerSocketConnection;

    private boolean mTrucking = true;

    public void startApp() {
        mDisplay = Display.getDisplay(this);
        mForm.addCommand(new Command("Exit", Command.EXIT, 0));
        mForm.setCommandListener(this);

        Thread t = new Thread(this);
        t.start();

        mDisplay.setCurrent(mForm);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        shutdown();
    }

    private void shutdown() {
        mTrucking = false;
        try {
            mServerSocketConnection.close();
        } catch (IOException ioe) {
        }
    }

    public void commandAction(Command c, Displayable s) {
        if (c.getCommandType() == Command.EXIT) {
            shutdown();
            notifyDestroyed();
        }
    }

    public void run() {
        try {
            mServerSocketConnection = (ServerSocketConnection) Connector.open("socket://:80");
            SocketConnection sc = null;
            while (mTrucking) {
                sc = (SocketConnection) mServerSocketConnection.acceptAndOpen();
                Reader in = new InputStreamReader(sc.openInputStream());

                PrintStream out = new PrintStream(sc.openOutputStream());
                out.print("HTTP/1.1 200 OK\r\n\r\n");
                out.print("Message");
                out.close();
                in.close();
                sc.close();
            }
        } catch (Exception e) {

        }
    }
}