Чат клиент-сервер с пользовательским интерфейсом - PullRequest
0 голосов
/ 30 октября 2018
        import java.awt.event.WindowEvent;

import javax.bluetooth.BluetoothStateException;

import com.intel.bluetooth.EmulatorTestsHelper;
import java.util.ArrayList;
import java.util.List;

import java.io.*;
import javax.bluetooth.DataElement;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import chatUI.ChatWindow;

public class Grafica3 implements Runnable {

    private static final UUID uuid = new UUID(0x1101);
    static int SERVICE_NAME_ATTRID = 0x0100;
    static String URL=null;

    public static void main(String args[]) {

         try {
            Grafica3 emulator = new Grafica3(); // Creamos el emulador para el servidor
             emulator.setUp(); //Arrancamos el emulador
             emulator.startClient(); //Ejecutamos los procesos Bluetooth como cliente
         } catch (Exception ex) {
             ex.printStackTrace();
         }    


        /* En este punto deberíamos buscar el servicio (en caso de que estemos en el cliente) y conectarnos a la URL
        o activar la escucha de peticiones (en el caso del servidor) */

        /* A continuación, obtenemos el inputStream y outputStream y los usamos desde la ventana */

        /* Invocamos la ventana (que se ejecuta como un thread en segundo plano) y 
         * definimos la acción de enviar lo que insertemos por teclado */





    }
    private static String entrada = "";
    private void startClient() throws IOException, InterruptedException {
        // TODO Auto-generated method stub

        List<RemoteDevice> devicesDiscovered = new ArrayList<RemoteDevice>();
        final Object inquiryCompletedEvent = new Object();

        devicesDiscovered.clear();

        DiscoveryListener listener = new DiscoveryListener() {

            public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                System.out.println("Device " + btDevice.getBluetoothAddress() + " found");
                devicesDiscovered.add(btDevice);
            }

            public void inquiryCompleted(int discType) {
                synchronized(inquiryCompletedEvent){
                    inquiryCompletedEvent.notifyAll();
                }
            }

            public void serviceSearchCompleted(int transID, int respCode) {
                synchronized(inquiryCompletedEvent){
                    inquiryCompletedEvent.notifyAll();
                }
            }

            public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
                for (int i = 0; i < servRecord.length; i++) {
                    String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                    if (url == null) {
                        continue;
                    }
                    DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
                    if (serviceName != null) {
                       System.out.println("Service name: " + serviceName.getValue() + ". Service url: " + url);
                       if(serviceName.getValue().equals("chat")) {
                           URL = url;
                       }
                    } else {
                       System.out.println("Service name: " + url);
                    }

                }
            }
        };

        synchronized(inquiryCompletedEvent) {
            boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
            if (started) {
                inquiryCompletedEvent.wait();
            }
        }
        if (!devicesDiscovered.isEmpty()){
                UUID uuids[] = new UUID[1];
                uuids[0] = new UUID(0x1101); // SerialPort
                int attridset[] = new int[1];
                attridset[0] = SERVICE_NAME_ATTRID;

                for (RemoteDevice d : devicesDiscovered) {
                    LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attridset, uuids, d, listener);
                    synchronized (inquiryCompletedEvent) {
                        inquiryCompletedEvent.wait();
                    }


                }


                if(URL != null) {

                    StreamConnection con = (StreamConnection) Connector.open(URL);
                    RemoteDevice dev = RemoteDevice.getRemoteDevice(con);


                    System.out.println("Cliente conectado al servidor");
                    System.out.println("BT Addres del servidor: "+dev.getBluetoothAddress());
                    System.out.println("Nombre del servidor: "+dev.getFriendlyName(true));

                    OutputStream os = con.openOutputStream();
                    InputStream is = con.openInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));

                     java.awt.EventQueue.invokeLater(new Runnable() {
                            public void run() {
                                final chatUI.ChatWindow _window;
                                _window = new ChatWindow();
                                _window.setVisible(true);
                                _window.addActionListener(new java.awt.event.ActionListener() {
                                    public void actionPerformed(java.awt.event.ActionEvent evt) {

                                        /* MODIFICAR EL CÓDIGO PARA EL ENVÍO AQUÍ */

                                        _window.setOut("Escriba un mensaje al servidor:");
                                        String entrada = _window.getIn();

                                        try {

                                        while(!entrada.equalsIgnoreCase("FIN.")) {
                                             entrada += "\n";
                                            os.write(entrada.getBytes());
                                            String respuesta = br.readLine();
                                            _window.setOut(respuesta);
                                            _window.setOut("\n\nMensaje recibido del servidor: "+respuesta);
                                            _window.setOut("Escriba un mensaje al servidor:");
                                            entrada = _window.getIn();
                                            _window.setOut(entrada);
                                            os.flush();
                                        }


                                        entrada += "\n";
                                        os.write(entrada.getBytes());

                                        con.close();

                                        }catch (Exception e) {}



                                    }
                                });




                                /*
                                 *
                                 * Líneas obligatorias: hay que registrar un listener para los eventos de ventana y
                                 * sobre el de window closing, realizar el cierre de conexiones.
                                 *
                                 *
                                 */

                                _window.addWindowListener(new java.awt.event.WindowListener() {
                                    public void windowClosing(WindowEvent e) {
                                        System.out.println("Window closing event .... close connections");
                                    }

                                    public void windowClosed(WindowEvent e) {
                                        System.out.println("Window closed event ");
                                    }

                                    public void windowDeactivated(WindowEvent e) {
                                        System.out.println("Window deactivated event ");
                                    }

                                    public void windowOpened(WindowEvent e) {
                                        System.out.println("Window event ");
                                    }

                                    public void windowIconified(WindowEvent e) {
                                        System.out.println("Window event ");
                                    }

                                    public void windowDeiconified(WindowEvent e) {
                                        System.out.println("Window event ");
                                    }

                                    public void windowActivated(WindowEvent e) {
                                        System.out.println("Window event ");
                                    }

                                });

                            }

                        });




                }




        }




    }


    private Thread serverThread;

    private void setUp() throws BluetoothStateException {
        // TODO Auto-generated method stub
         EmulatorTestsHelper.startInProcessServer();
         EmulatorTestsHelper.useThreadLocalEmulator();
         serverThread = EmulatorTestsHelper.runNewEmulatorStack(new Grafica3());
 }
    private static String mensaje = "";


    @Override
    public void run() {
        try {
            String url = "btspp://localhost:" + uuid.toString() + ";name=chat";
            StreamConnectionNotifier service = (StreamConnectionNotifier) Connector.open(url);
            System.out.println("INICIANDO EL SERVIDOR:"+url+"\n");
            LocalDevice ld = LocalDevice.getLocalDevice();
            System.out.println("Server info: " + ld.getBluetoothAddress() + " - " + ld.getFriendlyName()+"\n");
            System.out.println("Server iniciado, esperando a clientes...");
            StreamConnection con = (StreamConnection) service.acceptAndOpen();
            RemoteDevice dev = RemoteDevice.getRemoteDevice(con);
            InputStream is = con.openInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            OutputStream os = con.openOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
             java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        final chatUI.ChatWindow _window;
                        _window = new ChatWindow();
                        _window.setVisible(true);
                        _window.addActionListener(new java.awt.event.ActionListener() {
                            public void actionPerformed(java.awt.event.ActionEvent evt) {

                                /* MODIFICAR EL CÓDIGO PARA EL ENVÍO AQUÍ */
                                //String s = _window.getIn(); // metodo que lee de la entrada
                                //_window.setOut(s); //Método que escribe en la salida de la ventana
                                try {
                                String response = "";
                                mensaje = br.readLine();
                                mensaje.replaceAll("[\n\r]","");
                                _window.setOut(mensaje);

                                while (!mensaje.equals("FIN.")) {
                                    _window.setOut("\n\nMensaje recibido del cliente: "+dev.getBluetoothAddress() + " - " + dev.getFriendlyName(true) + ": " + mensaje+"");
                                    _window.setOut("Escribale un mensaje al cliente:");
                                    response =  _window.getIn();
                                    _window.setOut(response);
                                    bw.write(response);
                                    bw.newLine();
                                    bw.flush();
                                    mensaje = br.readLine();
                                    mensaje.replaceAll("[\n\r]","");
                                    _window.setOut(mensaje);
                                }
                                System.out.println("Device " + dev.getBluetoothAddress() + " - " + dev.getFriendlyName(true) + " disconnected successfully");
                                br.close();
                                bw.close();

                                mensaje = "";
                                con.close();


                            }catch(Exception e) {}
                            }
                        });



                        /*
                         *
                         * Líneas obligatorias: hay que registrar un listener para los eventos de ventana y
                         * sobre el de window closing, realizar el cierre de conexiones.
                         *
                         *
                         */

                        _window.addWindowListener(new java.awt.event.WindowListener() {
                            public void windowClosing(WindowEvent e) {
                                System.out.println("Window closing event .... close connections");
                            }

                            public void windowClosed(WindowEvent e) {
                                System.out.println("Window closed event ");
                            }

                            public void windowDeactivated(WindowEvent e) {
                                System.out.println("Window deactivated event ");
                            }

                            public void windowOpened(WindowEvent e) {
                                System.out.println("Window event ");
                            }

                            public void windowIconified(WindowEvent e) {
                                System.out.println("Window event ");
                            }

                            public void windowDeiconified(WindowEvent e) {
                                System.out.println("Window event ");
                            }

                            public void windowActivated(WindowEvent e) {
                                System.out.println("Window event ");
                            }

                        });

                    }
                });




        }catch(Exception e) {
            e.printStackTrace();
        }

    }


    }

Я пытаюсь создать клиент сервера чата с bluecove и графическим интерфейсом, но когда вы пытаетесь отправить одно сообщение, блокируйте программу, и я не знаю почему? Кто-нибудь может мне помочь?

...