import java.io.*; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; public class Chat extends MIDlet implements Runnable { private Thread t = new Thread(this); private StreamConnection sc1; private StreamConnection sc2; private InputStream is; private OutputStream os; private TextField tfHost = new TextField("Host:", "abc.def.com", 128, TextField.ANY); private TextField tfPort = new TextField("Port:", "1212", 128, TextField.ANY); private Display d; private Form f = new Form("Chat"); private StringItem siStatus = new StringItem("Status: ", ""); private StringItem siIn = new StringItem(null, ""); private TextField tfOut = new TextField(null, "Hello there!", 128, TextField.ANY); protected void startApp() throws MIDletStateChangeException { d = Display.getDisplay(this); f.append(siIn); f.append(tfOut); f.append(siStatus); Command c = new Command("Send", Command.SCREEN, 1); f.addCommand(c); f.setCommandListener(new C2()); setDisplayStart(); } protected void pauseApp() { } protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { try { is.close(); os.close(); sc1.close(); sc2.close(); notifyDestroyed(); } catch(Exception e) { } } public void run() { while(true) { try { boolean loop = true; StringBuffer sb = new StringBuffer(""); int x = 0; while(loop) { int ch = is.read(); if((ch != 10) & (ch != -1)) { x++; sb.append((char)ch); } else { loop = false; } } setDisplay("Received: " + x, sb.toString(), null); } catch(Exception e) { setDisplay("Error in receive!" + e, null, null); } } } private void connect() { try { String name = "socket://" + tfHost.getString() + ":" + tfPort.getString(); sc1 = (StreamConnection)Connector.open(name, Connector.READ); is = sc1.openInputStream(); sc2 = (StreamConnection)Connector.open(name, Connector.WRITE); os = sc2.openOutputStream(); setDisplay("Connected!", null, null); } catch(Exception e) { setDisplay("Not connected!", null, null); } t.start(); } private void send(String s) { s = s + "\r\n"; try { os.write(s.getBytes()); os.flush(); } catch(Exception e) { setDisplay("Error in send!" + e, null, null); } setDisplay("Sent: " + s.length(), null, ""); } private synchronized void setDisplay(String s1, String s2, String s3) { // In meddelanden if(s2 != null) siIn.setText(s2); // Ut meddelanden if(s3 != null) tfOut.setString(s3); //Status if(s1 != null) siStatus.setText(s1); d.setCurrent(f); } private void setDisplayStart() { Form fc = new Form("Connect"); fc.append(tfHost); fc.append(tfPort); Command c = new Command("Connect", Command.SCREEN, 1); fc.addCommand(c); fc.setCommandListener(new C1()); d.setCurrent(fc); } class C1 implements CommandListener { public void commandAction(Command c, Displayable d) { connect(); } } class C2 implements CommandListener { public void commandAction(Command c, Displayable d) { String s = tfOut.getString(); send(s); } } }