Created
November 24, 2010 17:31
-
-
Save pcdinh/714042 to your computer and use it in GitHub Desktop.
Socket.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package hello; | |
| import javax.microedition.midlet.*; | |
| import javax.microedition.io.*; | |
| import javax.microedition.lcdui.*; | |
| import java.io.*; | |
| /** | |
| * @author Pcdinh | |
| */ | |
| public class Socket extends MIDlet implements CommandListener { | |
| private boolean midletPaused = false; | |
| // StreamConnection allows bidirectional communication | |
| private StreamConnection conn = null; | |
| // use OutputStream to send requests | |
| private OutputStream outputStream = null; | |
| private DataOutputStream out = null; | |
| // use InputStream to receive responses from Web server | |
| private InputStream inputStream = null; | |
| private DataInputStream in = null; | |
| // specify the connect string | |
| private String url = "socket://localhost:8687"; | |
| // define GUI components | |
| private Display display = null; | |
| private Form resultScreen; | |
| private StringItem resultField; | |
| private Command serverReplyBackCommand; | |
| private Command serverReplyExitCommand; | |
| //<editor-fold defaultstate="collapsed" desc=" Generated Fields "> | |
| private Command exitCommand; | |
| private Form form; | |
| private StringItem stringItem; | |
| //</editor-fold> | |
| /** | |
| * The Socket constructor. | |
| */ | |
| public Socket() { | |
| // initializing GUI display | |
| display = Display.getDisplay(this); | |
| this.initialize(); | |
| } | |
| //<editor-fold defaultstate="collapsed" desc=" Generated Methods "> | |
| //</editor-fold> | |
| //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize "> | |
| /** | |
| * Initializes the application. | |
| * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method. | |
| */ | |
| private void initialize() { | |
| // Commands | |
| serverReplyExitCommand = new Command("Exit", Command.EXIT, 0); | |
| serverReplyBackCommand = new Command("Back", Command.BACK, 0); | |
| // The display form | |
| resultScreen = new Form("Server Reply"); | |
| resultScreen.addCommand(serverReplyBackCommand); | |
| resultScreen.addCommand(serverReplyExitCommand); | |
| resultScreen.setCommandListener(this); | |
| // write post-initialize user code here | |
| } | |
| //</editor-fold> | |
| //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet "> | |
| /** | |
| * Performs an action assigned to the Mobile Device - MIDlet Started point. | |
| */ | |
| public void startMIDlet() { | |
| // write pre-action user code here | |
| switchDisplayable(null, getForm()); | |
| // write post-action user code here | |
| } | |
| //</editor-fold> | |
| //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet "> | |
| /** | |
| * Performs an action assigned to the Mobile Device - MIDlet Resumed point. | |
| */ | |
| public void resumeMIDlet() { | |
| // write pre-action user code here | |
| // write post-action user code here | |
| } | |
| //</editor-fold> | |
| //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable "> | |
| /** | |
| * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable. | |
| * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately | |
| * @param nextDisplayable the Displayable to be set | |
| */ | |
| public void switchDisplayable(Alert alert, Displayable nextDisplayable) { | |
| // write pre-switch user code here | |
| Display display = getDisplay(); | |
| if (alert == null) { | |
| display.setCurrent(nextDisplayable); | |
| } else { | |
| display.setCurrent(alert, nextDisplayable); | |
| } | |
| // write post-switch user code here | |
| } | |
| //</editor-fold> | |
| //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables "> | |
| /** | |
| * Called by a system to indicated that a command has been invoked on a particular displayable. | |
| * @param command the Command that was invoked | |
| * @param displayable the Displayable where the command was invoked | |
| */ | |
| public void commandAction(Command command, Displayable displayable) { | |
| if (displayable == resultScreen) { | |
| if (command == serverReplyExitCommand) { | |
| // write pre-action user code here | |
| exitMIDlet(); | |
| // write post-action user code here | |
| } | |
| } | |
| if (displayable == form) { | |
| if (command == exitCommand) { | |
| // write pre-action user code here | |
| exitMIDlet(); | |
| // write post-action user code here | |
| } | |
| } | |
| // write post-action user code here | |
| } | |
| //</editor-fold> | |
| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand "> | |
| /** | |
| * Returns an initiliazed instance of exitCommand component. | |
| * @return the initialized component instance | |
| */ | |
| public Command getExitCommand() { | |
| if (exitCommand == null) { | |
| // write pre-init user code here | |
| exitCommand = new Command("Exit", Command.EXIT, 0); | |
| // write post-init user code here | |
| } | |
| return exitCommand; | |
| } | |
| //</editor-fold> | |
| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form "> | |
| /** | |
| * Returns an initiliazed instance of form component. | |
| * @return the initialized component instance | |
| */ | |
| public Form getForm() { | |
| if (form == null) { | |
| // write pre-init user code here | |
| form = new Form("Welcome", new Item[] { getStringItem() }); | |
| form.addCommand(getExitCommand()); | |
| form.setCommandListener(this); | |
| // write post-init user code here | |
| } | |
| return form; | |
| } | |
| //</editor-fold> | |
| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem "> | |
| /** | |
| * Returns an initiliazed instance of stringItem component. | |
| * @return the initialized component instance | |
| */ | |
| public StringItem getStringItem() { | |
| if (stringItem == null) { | |
| // write pre-init user code here | |
| stringItem = new StringItem("Hello", "Hello, World!"); | |
| // write post-init user code here | |
| } | |
| return stringItem; | |
| } | |
| //</editor-fold> | |
| /** | |
| * Returns a display instance. | |
| * @return the display instance. | |
| */ | |
| public Display getDisplay() { | |
| return Display.getDisplay(this); | |
| } | |
| /** | |
| * Exits MIDlet. | |
| */ | |
| public void exitMIDlet() { | |
| switchDisplayable(null, null); | |
| destroyApp(true); | |
| notifyDestroyed(); | |
| } | |
| /** | |
| * Called when MIDlet is started. | |
| * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet. | |
| */ | |
| public void startApp() { | |
| try { | |
| // establish a Socket connection with remote server | |
| conn = (StreamConnection) Connector.open(url, Connector.READ_WRITE); | |
| // create DataOuputStream on top of the Socket connection | |
| outputStream = conn.openOutputStream(); | |
| out = new DataOutputStream(outputStream); | |
| // create DataInputStream on top of the Socket connection | |
| inputStream = conn.openInputStream(); | |
| in = new DataInputStream(inputStream); | |
| int firstChar = in.read(); | |
| // EOF: firstChar == -1 | |
| // Connected | |
| if (firstChar == (int) '^') { | |
| System.out.println("Connected"); | |
| // send the HTTP request | |
| inputStream.skip(2); // skip \r\n | |
| out.write("GET news_detail id:59\n".getBytes()); | |
| out.flush(); | |
| // retrieve the contents | |
| String encoding = System.getProperty("microedition.encoding"); | |
| System.out.println(encoding); | |
| // Detects response type | |
| firstChar = in.read(); | |
| if (firstChar == (int) '#') { // single data load | |
| System.out.println("Data load found"); | |
| int byteCount = ByteReaderUtil.getInt(in); | |
| ByteArrayOutputStream bout = new ByteArrayOutputStream(); | |
| byte[] tmp = new byte[byteCount]; | |
| bout.write(tmp, 0, in.read(tmp)); | |
| String dataOut = new String(bout.toByteArray(), "UTF-8"); | |
| System.out.println(dataOut); | |
| // display the page contents on the phone screen | |
| resultField = new StringItem(null, dataOut); | |
| resultScreen.append(resultField); | |
| display.setCurrent(resultScreen); | |
| } else if (firstChar == (int) '=') { | |
| System.out.println("Bad command"); | |
| } else if (firstChar == (int) '!') { | |
| System.out.println("Something caused errors in the server side"); | |
| } else if (firstChar == (int) '?') { | |
| System.out.println("Something wrong with the client command that was sent to the server. The command must be corrected."); | |
| } else { | |
| // Invalid reponse type from the server. Things changed in the protocol specs. Please ask the developer who wrote the server code. | |
| System.out.println(firstChar); | |
| } | |
| } | |
| } catch (IOException ex) { | |
| ex.printStackTrace(); | |
| } catch (InvalidResponseException ex) { | |
| ex.printStackTrace(); | |
| } catch (NumberFormatException ex) { | |
| ex.printStackTrace(); | |
| } finally { | |
| // free up I/O streams and close the Socket connection | |
| try { | |
| if (in != null) { | |
| in.close(); | |
| } | |
| } catch (Exception ignored) { | |
| } | |
| try { | |
| if (out != null) { | |
| out.close(); | |
| } | |
| } catch (Exception ignored) { | |
| } | |
| try { | |
| if (outputStream != null) { | |
| outputStream.close(); | |
| } | |
| } catch (Exception ignored) { | |
| } | |
| try { | |
| if (inputStream != null) { | |
| inputStream.close(); | |
| } | |
| } catch (Exception ignored) { | |
| } | |
| try { | |
| if (conn != null) { | |
| conn.close(); | |
| } | |
| } catch (Exception ignored) { | |
| } | |
| } | |
| } | |
| /** | |
| * Called when MIDlet is paused. | |
| */ | |
| public void pauseApp() { | |
| midletPaused = true; | |
| } | |
| /** | |
| * Called to signal the MIDlet to terminate. | |
| * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released. | |
| */ | |
| public void destroyApp(boolean unconditional) { | |
| } | |
| } | |
| /** | |
| * TTMobile protocol aware byte reader utility. | |
| * | |
| * @author pcdinh | |
| */ | |
| final class ByteReaderUtil { | |
| /** | |
| * Reads a string that represents an integer until \r\n is found. | |
| * | |
| * @param in | |
| * @return The number found | |
| * @throws IOException | |
| * @throws InvalidResponseException | |
| * @throws NumberFormatException the string to read does not represent a number | |
| */ | |
| public static int getInt(final InputStream in) throws IOException, InvalidResponseException, NumberFormatException { | |
| final StringBuffer sb = new StringBuffer(); | |
| int cc; | |
| while ((cc = in.read()) != -1) { | |
| // Number | |
| if (cc >= 48 && cc <= 57) { | |
| sb.append((char) cc); | |
| continue; | |
| } | |
| if (cc == 13) { // \r | |
| if (in.read() == 10) { // \n | |
| break; | |
| } | |
| } | |
| throw new InvalidResponseException(); | |
| } | |
| System.out.println(sb.toString()); | |
| return Integer.parseInt(sb.toString()); | |
| } | |
| } | |
| class InvalidResponseException extends Exception { | |
| public InvalidResponseException() { | |
| super(); | |
| } | |
| public InvalidResponseException(String message) { | |
| super(message); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment