Read/Write on PC !!!

rub1s
2005-10-18
2013-04-15
  • rub1s
    rub1s
    2005-10-18

    Hi,

    I've to develope a chat with Bluetooth in a Cliet/Server Architeture. The client is a cell phone and the server is a Pc. I'm using J2ME for the client and the package javax.bluetoothm, for the Server I'm using Linux, J2SE and AvetanaBT. I've a problem, when the client send the messages to the server, this can't show them in the screen at the same time that the client send them, it happens when the client closes the conections.

    How can I solve this problem?

    Client code:

    public class AuthenticationUI extends Form implements CommandListener{
        private MainMIDlet midlet=null;
        private NetBT netbt;

        private TextField textfieldlogin = null;
        private TextField textfieldpass = null;
        private Command ok = null;
        private Command back= null;

        private DataInputStream dinput=null;
        private DataOutputStream doutput=null;
        private StreamConnection conn=null;

        public AuthenticationUI(MainMIDlet m){
            super("");
            midlet=m;
            //start new thread connect to server
            netbt=new NetBT();
            new Thread(netbt).start();
            ok= new Command("Ok",Command.OK,1);
            back = new Command("Atrs",Command.BACK,2);
            textfieldlogin = new TextField("Login:","",5,TextField.ANY);
            textfieldpass = new TextField("Password:","",4,TextField.PASSWORD);
            this.append(textfieldlogin);
            this.append(textfieldpass);
            this.addCommand(ok);
            this.addCommand(back);
            this.setCommandListener(this);
        }

        public void commandAction(Command c, Displayable d){
            if (c == ok){   
                String cad=textfieldlogin.getString()+" "+textfieldpass.getString();
                dinput=netbt.getDataInputStream();
                doutput=netbt.getDataOutputStream();
                //Send the login and password
                new Thread(new LoginPassSend(cad,dinput,doutput)).start();
            }else if (c == back){
                //Acciones para Regresar
                midlet.showUIMenu();
            }
        }
    }

    /** Send the login and password to server
    **/
    class LoginPassSend implements Runnable{
        private DataInputStream din;
        private DataOutputStream dout;
        private String message;

        public LoginPassSend(String loginpass,DataInputStream in, DataOutputStream out){
            message=loginpass;
            din=in;
            dout=out;
        }

        public void run(){
            try{
                dout.writeUTF("SendLoginPass");
                dout.flush();
                dout.writeUTF(message);
                dout.flush();
            }catch(IOException ioe){
            }
        }
    }

    /** Create the connection to server
    **/
    class NetBT implements Runnable{

        private DataInputStream dinput=null;
        private DataOutputStream doutput=null;
        private StreamConnection conn=null;

        public NetBT(){
            super();
        }
       
        /** Create the connection to server
        **/
        public void run(){
            String connString = getConnectionString();
            connectToServer(connString);
        }
       
        /** Create string connection to server
           @return string connection
        **/
        private String getConnectionString(){
            StringBuffer temp = new StringBuffer("btspp://000A3A570270:1");

            return temp.toString();
        }

        /** Connect to server
          @ param connString String connection
          @ return true if connection is ok,otherside false  
        **/
        private boolean connectToServer (String connString){
            try{

              conn = (StreamConnection) Connector.open(connString);

              dinput = conn.openDataInputStream();
              doutput = conn.openDataOutputStream();

              return true;
            }catch (IOException ioe){
              return false;
            }
        }
        /** Return DataInputStream
        **/
        public DataInputStream getDataInputStream(){
            return dinput;
        }
        /** Return DataOutputStream
        **/
        public DataOutputStream getDataOutputStream(){
            return doutput;
        }
    }

    The side Server code:

    public class EchoServer extends JFrame implements ActionListener{
      private JPanel contentPane;
      public JTextArea TextArea_chat = new JTextArea("");
      private JButton Button_service = new JButton("New Service");
      private JButton Button_conexion = new JButton("Conectar");
      private JButton Button_cerrar = new JButton("Cerrar");
      private JButton Button_write = new JButton("Escribir");
      private JButton Button_leer = new JButton("Leer");
      private JTextField TextField_message = new JTextField("");
      private JScrollPane jScrollPane1 = new JScrollPane();

      //********* Variables para bluetooth
       private Connection notify = null,streamCon=null;
       private JSR82URL url=null;
       private DataOutputStream doutput=null;
       private DataInputStream dinput=null;

       private boolean doread=false;

      public EchoServer() {
        try {
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          jbInit();
        }
        catch (Exception exception) {
          exception.printStackTrace();
        }
      }

      /**
       * Component initialization.
       *
       * @throws java.lang.Exception
       */
      private void jbInit() throws Exception {
        contentPane = (JPanel) getContentPane();
        contentPane.setLayout(null);
        setSize(new Dimension(400, 300));
        setTitle("Servidor Escucha");
        TextArea_chat.setLineWrap(true);

        Button_conexion.setBounds(new Rectangle(270, 33, 108, 27));
        jScrollPane1.setBounds(new Rectangle(6, 5, 261, 263));
        Button_service.setBounds(new Rectangle(270, 2, 108, 29));
        Button_cerrar.setBounds(new Rectangle(270, 120, 105, 25));
        Button_leer.setBounds(new Rectangle(270, 62, 106, 25));
        Button_write.setBounds(new Rectangle(269, 89, 105, 28));
        TextField_message.setBounds(new Rectangle(8, 271, 390, 23));

        contentPane.add(jScrollPane1);
        contentPane.add(Button_service);
        contentPane.add(Button_conexion);
        contentPane.add(Button_leer);
        contentPane.add(Button_write);
        contentPane.add(Button_cerrar);
        contentPane.add(TextField_message);
        jScrollPane1.getViewport().add(TextArea_chat);

        //Agrega los listener para los botones conectar y servicio
        this.addListeners();
      }

      /** Close connections and stream in/out
       * **/
      private void closeConnections() throws Exception{
        doutput.close();
        dinput.close();
        streamCon.close();
        notify.close();
      }

      /** Add listener to button
       * **/
      private void addListeners(){
        Button_conexion.addActionListener(this);
        Button_service.addActionListener(this);
        Button_cerrar.addActionListener(this);
        Button_leer.addActionListener(this);
        Button_write.addActionListener(this);
      }

      /**
       * **/
      public void actionPerformed(ActionEvent e) {
        try {
          if (e.getSource() == Button_conexion){
            try{
              this.CreateConnection();
            }catch (IOException ioe){
              JOptionPane.showMessageDialog(this, "Problemas al crear la conexin: " + ioe.getMessage(),
                                        "Error", JOptionPane.ERROR_MESSAGE);
            }
          }else if (e.getSource() == Button_service){
           try{
             this.CreateService();
           }catch (IOException ioe){
             JOptionPane.showMessageDialog(this, "Problema al crear el servicio: " + ioe.getMessage(),
                                  "Error", JOptionPane.ERROR_MESSAGE);
           }
          } else if (e.getSource() == Button_cerrar){
            try{
              this.closeConnections();
            }catch (IOException ioe){
              JOptionPane.showMessageDialog(this, "Cerrar las conexiones: "+ ioe.getMessage(),
                                  "Error", JOptionPane.ERROR_MESSAGE);
            }
          } else if (e.getSource() == Button_leer){
              this.ReadData();
          }else if (e.getSource() == Button_write){
            try{
              this.WriteMessage(TextField_message.getText());
            }catch(IOException ioe) {
              JOptionPane.showMessageDialog(this, "Escribir datos del cliente: "+ ioe.getMessage(),
                                            "Error", JOptionPane.ERROR_MESSAGE);
            }
          }
        }catch (Exception e2) {
          e2.printStackTrace();
        }
      }

      /** Send the messaje to client
       * **/
      private void WriteMessage(String message) throws Exception{
        doutput.writeUTF(message);
        doutput.flush();
        TextArea_chat.append(">> "+message+"\n");
        TextField_message.setText("");
      }

      /** Wait that client connect to service
       * **/
      private void CreateConnection() throws Exception{
          streamCon = ( (StreamConnectionNotifier) notify).acceptAndOpen();

          dinput = ((StreamConnection)streamCon).openDataInputStream();
          doutput = ((StreamConnection)streamCon).openDataOutputStream();

      }

      /** Create the service
       * **/
      private void CreateService() throws Exception{
          url = new JSR82URL(
              "btspp://localhost:ce37ca6e288a409a9796191882ee44fc;name=Echo Server");
          notify = (ConnectionNotifier) Connector.open(url.toString());
      }

      /** Read data to client
       * **/
      private void ReadData() throws Exception{
        while(!doread){
          String cad=dinput.readUTF();
          if (cad.equals("Cerrar")){
            //close connection
            doread = true;
            TextArea_chat.append("La conexin fue cerrada\n");
          } else
            TextArea_chat.append("<< "+cad+"\n");
        }
      }
    }

    Thanks