////////////////////////// //ChatMidlet.java //importing some java package ////////////////////////// import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*; ///////////// //ChatMidlet extending abstract MIDlet class with CommandListener and Runnable Thread ///////////// public class ChatMidlet extends MIDlet implements Runnable, CommandListener { //declaring some displayable private Display display; private Form mainform, newChat, composeMessage; private TextField listeningPort, message, location, nickname; private Command ok, start, exit, cancel, reply, send; private Ticker ticker; private List ChatSession; //flags String msgSend, destination, nick; ///////////// //Constructor ///////////// public ChatMidlet() { ///New Chat Form newChat = new Form("BlueChat Initilization..."); ChatSession = new List("BlueChat Messages", List.IMPLICIT); listeningPort = new TextField("Create new chat session over datagram port(this serves as the listening port):","",5, TextField.NUMERIC); nickname = new TextField("Nickname:","",100, TextField.ANY); message = new TextField("Message:","",100, TextField.ANY); location = new TextField("Send to (IP address:port):","",50, TextField.ANY); ///Commands exit = new Command("Exit", Command.EXIT, 1); send = new Command("Send", Command.SCREEN, 1); start = new Command("Start", Command.SCREEN , 1); cancel = new Command("Cancel", Command.CANCEL, 1); reply = new Command("Reply", Command.SCREEN , 1); ok = new Command("Ok", Command.SCREEN , 1); ///Compose message composeMessage = new Form("BlueChat: Compose Message"); composeMessage.append(location); composeMessage.append(message); composeMessage.addCommand(send); composeMessage.addCommand (cancel); composeMessage.setCommandListener(this); ///Main Form mainform = new Form("BlueChat"); //Appending image/logo in the main form try { Image img = Image.createImage("/bluechatlogo.jpg"); //Image img = Image.createImage("/bluechatlogo.png"); ImageItem image = new ImageItem("\n\n\n\n", img, Item.LAYOUT_CENTER, "BlueChat"); mainform.append(image); } catch (Exception e){e.printStackTrace();} mainform.addCommand(ok); mainform.addCommand(exit); mainform.setCommandListener(this); } ///////////// //Start up function ///////////// public void startApp() { if (display == null) { display = Display.getDisplay(this); display.setCurrent(mainform); } } ///////////// //Pause application function ///////////// public void pauseApp() { } ///////////// //Destroy application function ///////////// public void destroyApp(boolean unconditional){ } ///////////// //Command action function which works with the CommandListener interface ///////////// public void commandAction(Command c, Displayable d) { //Exit Command if (c == exit){ notifyDestroyed(); } //Okay Command if (c == ok) { newChat.append(listeningPort); newChat.append(nickname); newChat.addCommand(start); newChat.addCommand(exit); newChat.setCommandListener (this); display.setCurrent(newChat); } //Start Command if (c == start) { nick = nickname.getString(); ticker=new Ticker("You are listening to port "+listeningPort.getString()+ ", "+nick); ChatSession.setTicker(ticker); ChatSession.addCommand(reply); ChatSession.addCommand(exit); ChatSession.setCommandListener(this); display.setCurrent(ChatSession); new Thread( this ).start(); } //Cancel Command if (c == cancel) { display.setCurrent(ChatSession); } //Reply Message Command if (c == reply) { int pointer = ChatSession.getSelectedIndex(); String[] stringMsg; String wholeMsg, locationOfSender=""; if(pointer >= 0) { wholeMsg = ChatSession.getString (pointer); stringMsg = split(wholeMsg, '('); locationOfSender = stringMsg[1]; stringMsg = split(locationOfSender, ')'); locationOfSender = stringMsg[0].trim(); } location.setString(""+locationOfSender); message.setString (""); nickname.setString(""); display.setCurrent(composeMessage); } //Send Message Command if (c == send) { msgSend = message.getString(); destination = location.getString(); new Thread( this ).start(); send(msgSend); } } ///////////// //Send Message function using datagram connection ///////////// void send(String msg) { UDPDatagramConnection datagramcon = null; String localhost = "datagram://localhost:777"; try { datagramcon = (UDPDatagramConnection) Connector.open(localhost); msg="From: " + nick + " (" + datagramcon.getLocalAddress()+":"+listeningPort.getString()+")\nMessage: "+ msg; int length = msg.length(); byte[] MessageToSend = msg.getBytes(); Datagram data = datagramcon.newDatagram (MessageToSend, length, "datagram://"+destination); datagramcon.send (data); } catch (Exception e) { System.out.println("Failed to send message: " + e); } finally { if (datagramcon != null) { try { datagramcon .close(); } catch (Exception error) { System.out.println ("Failed to close Connector: " + error); } } } } ///////////// //Split String Utility to parse IP and port number of the sender // Utility routine to split a string into two from http://java.sun.com/developer/J2METechTips/2002/tt0131.html ///////////// static String[] split( String in, char ch ){ String[] result = new String[2]; int pos = in.indexOf( ch ); if( pos != -1 ){ result[0] = in.substring( 0, pos ).trim(); result[1] = in.substring( pos+1 ).trim(); } else { result[0] = in.trim(); } return result; } ///////////// //Thread Runnable implementing UDPDtagramConnection serves as a listener for incoming messages ///////////// public void run() { UDPDatagramConnection datagramListener = null; Datagram msg = null; try { datagramListener = (UDPDatagramConnection) Connector.open("datagram://:"+listeningPort.getString()); String msgReceive; while(true) { msg = datagramListener.newDatagram(datagramListener.getMaximumLength()); try { datagramListener.receive (msg); } catch (Exception e) { } String data = new String(msg.getData(), 0, msg.getLength()); ChatSession.append(data.trim(),null); } } catch (Exception e) { } finally { if (datagramListener != null) { try { datagramListener.close(); } catch (Exception error) { System.out.println("Failed to close Connector: " + error); } } } } }