dinjo 0 Newbie Poster

Hi

I am trying to design a chat room using netbeans, I have been able to get 1 client to communicate with the server..please how do I create multiple clients and then enable them to broadcast messages to all other clients using UDP.

My codes are below:

package MobileServer;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

import java.io.*;
import javax.microedition.io.*;


public class ServerMidlet extends MIDlet implements CommandListener{
    private Display display;
    private Form serverForm;
    private StringItem st;
    private TextField receivedText;
    private TextField transmitText;
    private String receiveMessage;
    private DatagramConnection dc;
    private boolean dataAvailable;
    private boolean connected;
    private CommunicationThread ct;
    private String clientAddress;
    static final String address = "datagram://:8000"; 
    static final Command exitCommand = new Command("Exit", Command.EXIT,0);
    static final Command transmittCommand = new Command("Transmit", Command.OK,1);
    
    public ServerMidlet() {
            serverForm = new Form("Server.");
            st = new StringItem("","Awaiting Client Connection");
            receivedText = new TextField("Received Text:","",32,TextField.UNEDITABLE);
            transmitText = new TextField("Transmit Text:","",32,TextField.UNEDITABLE);
            dc = null;
            serverForm.append(st);
            serverForm.append(receivedText);
            serverForm.append(transmitText);
            serverForm.addCommand(exitCommand);
            serverForm.addCommand(transmittCommand);
            serverForm.setCommandListener(this);
            connected = false;
            dataAvailable = false;
        }
    public void startApp() {
        display = Display.getDisplay(this);
        display.setCurrent(serverForm);
        while (dc == null)
            {
            try {
                dc = (DatagramConnection)Connector.open(address);
                }
            catch (IOException iex){
                receivedText.setString(iex.getMessage());
                }
            }
        ct = new CommunicationThread(this);
        ct.start();
        }
    
    public void pauseApp() {
        }
    
    public void destroyApp(boolean unconditional) {
         try {
            dc.close();
            }
        catch (Exception e) {
            receivedText.setString(e.getMessage());
            }
        notifyDestroyed();
        }
    
    public void commandAction(Command c, Displayable d) {
        String event = null;
        event = c.getLabel();
        if (event.equals("Transmit")&connected)
            synchronized (this) {
                dataAvailable = true;
                notify();
                }
        else if (event.equals("Exit"))
            destroyApp(true);
        }
    
public class CommunicationThread extends Thread {
   	private MIDlet parent;

    	public CommunicationThread(MIDlet parent) {
            this.parent = parent;
            }
    	
        public void run() {
            while (true) {
                synchronized(parent) {
                    while (!connected)
                        RecieveMessage();
                    while (!dataAvailable) {
                        try {
                            parent.wait();
                            }
                        catch (InterruptedException e) {
                            receivedText.setString(e.getMessage());
                            }
                        }
                    TransmitMessage();
                    RecieveMessage();
                    dataAvailable = false;
                    }
                }
            }

    	public void TransmitMessage() {
            try {
                transmitText.setConstraints(TextField.UNEDITABLE);
                byte[] data = transmitText.getString().getBytes();
                Datagram dg = null; 
                dg = dc.newDatagram(data, data.length, clientAddress);
                dc.send(dg);
                transmitText.setString("");
                st.setText("Awaiting Reply from client.");
                }
            catch (Exception e) {
                receivedText.setString(e.getMessage());
                }
            }

   	public void RecieveMessage() {
            try {
                Datagram dg = dc.newDatagram(32);
                dc.receive(dg);
                if (dg.getLength() > 0) {
                    transmitText.setConstraints(TextField.ANY);
                    connected = true;
                    clientAddress = dg.getAddress();
                    receiveMessage = new String(dg.getData(), 0 , dg.getLength());
                    receivedText.setString(receiveMessage); 
                    st.setText("Client Connected: Transmit to client.");
                    }
                }
            catch (Exception e) {
                receivedText.setString(e.getMessage());
                }		
            }
    }
}
package MobileClient;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;


public class ClientMidlet extends MIDlet implements CommandListener {
    
   private Display display;
   private Form loginForm;
   private TextField userName;
   private TextField passWord;
   private String user="FIRESTAR";
   private String userPassWord="2122";
   private Image image1,image2;
   private Alert alert1,alert2;
   private Form serverForm;
   private StringItem st;
   private TextField receivedText;
   private TextField transmitText;
   private String receiveMessage;
   private DatagramConnection dc;
   private boolean dataAvailable;
   private CommunicationThread ct;
   static final Command loginCommand=new Command("Login",Command.OK,0);

   static final String address = "datagram://localhost:8000";
   static final Command exitCommand = new Command("Exit", Command.EXIT,2);
   static final Command transmittCommand = new Command("Transmit", Command.OK,1);
    
   public ClientMidlet()throws IOException {
       loginForm = new Form("Login Screen");
       userName = new TextField("LoginID:","",20,TextField.ANY);
       passWord = new TextField("Password:","",20,TextField.PASSWORD);
       loginForm.append(userName);
       loginForm.append(passWord);
       image1= Image.createImage("/res/Hello.png");
       image2= Image.createImage("/res/Goodbye.png");
       alert1= new Alert("Login Error","User name or password incorrect.",image2,AlertType.ERROR);
       alert2= new Alert("Login Successful","Connected",image1,AlertType.CONFIRMATION);
       loginForm.addCommand(exitCommand);
       loginForm.addCommand(loginCommand);
       loginForm.setCommandListener(this);
       serverForm = new Form("Client.");
            st = new StringItem("","");
            receivedText = new TextField("Received Text:","",32,TextField.UNEDITABLE);
            transmitText = new TextField("Transmit Text:","",32,TextField.ANY);
            dc = null;
            serverForm.append(st);
            serverForm.append(receivedText);
            serverForm.append(transmitText);
            serverForm.addCommand(exitCommand);
            serverForm.addCommand(transmittCommand);
            serverForm.setCommandListener(this);
            dataAvailable = false;
        }
   
    public void startApp() {
        display = Display.getDisplay(this);
        DisplayLoginMenu();
    
        }
    
    public void pauseApp() {
        }
    
    public void destroyApp(boolean unconditional) {
        try {
            dc.close();
            }
        catch (Exception e) {
            receivedText.setString(e.getMessage());
            }
        notifyDestroyed();
        }
    public void DisplayLoginMenu(){
        display.setCurrent(loginForm);
    }
    public void ClientForm(){
            display.setCurrent(loginForm);
        display.setCurrent(serverForm);
        while (dc == null){
            try {
                dc = (DatagramConnection)Connector.open(address);
                }
            catch (IOException iex){
                receivedText.setString(iex.getMessage());
                }
            }
        ct = new CommunicationThread(this);
        ct.start();
        st.setText("Transmit to Server");
    }
    public void commandAction(Command c, Displayable d) {
        String event = null;
        event = c.getLabel();
          Alert alert = new Alert("","",image1,AlertType.CONFIRMATION);
          if (event.equals("Login"))
          {
         if((userName.getString().toUpperCase().equals(user))&&(passWord.getString().toUpperCase().equals(userPassWord)))
              {
                 ClientForm();
              }
     else
              display.setCurrent(alert1,loginForm);
          }
        if (event.equals("Transmit"))
              synchronized (this) {
                    dataAvailable = true;
                    notify();
                    }
        else if (event.equals("Exit"))
            destroyApp(true);
        }
     public class CommunicationThread extends Thread {
   	private MIDlet parent;
    	public CommunicationThread(MIDlet parent) {
      		this.parent = parent;
    		}
    	public void run() {
      		while (true) {
        		synchronized(parent) {
                            while (!dataAvailable) {
                                try {
                                    parent.wait();
                                    }
                                catch (InterruptedException e){
                                    receivedText.setString(e.getMessage());
                                    }
                                }
                            TransmitMessage();
                            RecieveMessage();
                            dataAvailable = false;
                            }
                        }
                    }
        
    	public void TransmitMessage(){
      		try 	{
                        transmitText.setConstraints(TextField.UNEDITABLE);
                        byte[] data = transmitText.getString().getBytes();
                        Datagram dg = null; 
                        dg = dc.newDatagram(data, data.length);
                        dc.send(dg);
                        transmitText.setString("");
                        st.setText("Awaiting Reply from server.");
                        }
     		catch (Exception e) {
                        receivedText.setString(e.getMessage());
                        }
     		}

   	public void RecieveMessage(){
            try {
                Datagram dg = dc.newDatagram(32);
                dc.receive(dg);
                if (dg.getLength() > 0) {
                    transmitText.setConstraints(TextField.ANY);
                    receiveMessage = new String(dg.getData(), 0 , dg.getLength());
                    receivedText.setString(receiveMessage); 
                    st.setText("Transmit to server.");
                    }
                }
            catch (Exception e) {
                receivedText.setString(e.getMessage());
                }		
            }
        }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.