-2

I have a problem that I think is easy but I don't know how to resolve.

If my client executes with the argument -p, the server creates a file from the database and returns it to the client. If the client has no arguments then it sends a serializable object the the server and the server saves it in the database.

My client code:

public class cliente {
    public static void main(String[] args) {

        // común
        String hostname = "localhost";
        int port = 6789;
        Socket clientSocket = null;

        // descarga fichero
        String ficheroDescargado = null;

        // Almacena datos
        BufferedReader br = null;
        ObjectOutputStream os = null;
        String str = "";
        Map<DatosAEnviar, DatosAEnviar> datos = new TreeMap<DatosAEnviar, DatosAEnviar>();

        if (args.length != 0 && args[0] == "-p") {
            System.out.println("Descarga fichero");
            try {
                // Instanciamos la conexión con el socket
                clientSocket = new Socket(hostname, port);
                System.out.println("IP " + clientSocket.getInetAddress().toString());
                ficheroDescargado = "descarga_tienda_"
                        + clientSocket.getInetAddress().toString()
                                .replace("localhost/", "") + ".txt";
                byte[] mybytearray = new byte[1024];
                InputStream is = clientSocket.getInputStream();
                FileOutputStream fos = new FileOutputStream(ficheroDescargado);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                int bytesRead = is.read(mybytearray, 0, mybytearray.length);
                bos.write(mybytearray, 0, bytesRead);
                bos.close();
                // Cerramos el socket
                clientSocket.close();
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: " + hostname);
            } catch (IOException e) {
                System.err.println("Por favor, inicialice primero el servidor "
                        + hostname);
            }
        } else {
            System.out.println("Leer fichero");
            datos = leerFichero();
            System.out.println("Pintamos lo recibido");
            for (Entry<DatosAEnviar, DatosAEnviar> itrDatos : datos.entrySet()) {
                DatosAEnviar clave = itrDatos.getKey();
                DatosAEnviar valor = itrDatos.getValue();
                System.out.println(clave + "  ->  " + valor.toString());
            }
            try {
                // Instanciamos la conexión con el socket
                clientSocket = new Socket(hostname, port);
                // Abrimos el canal entrada de datos. Nos la enviará el servidor
                // para confirmar que ha procesado OK
                br = new BufferedReader(new InputStreamReader(
                        clientSocket.getInputStream()));
                // Abrimos el canal de salida para mandar al servidor la
                // colección
                // MapTree
                os = new ObjectOutputStream(clientSocket.getOutputStream());
                // Enviamos por el canal de salida hacia el servidor los daros
                // en el
                // MapTree
                os.writeObject(datos);
                // Esperamos la respuesta del servidor.
                while ((str = (String) br.readLine()) != null) {
                    System.out.println(str);
                    if (str.equals("bye"))
                        break;
                }
                // Cerramos el canal de salida
                os.close();
                // Cerramos el canal de entrada
                br.close();
                // Cerramos el socket
                clientSocket.close();
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: " + hostname);
            } catch (IOException e) {
                System.err.println("Por favor, inicialice primero el servidor"
                        + hostname);
            }
        }
    }

The client is ok and works fine. The problem is in the server:

My Server Code:

public class Server2 {
    public static void main(String args[]) {
        int port = 6789;
        Server2 server = new Server2(port);
        server.startServer();
    }

    // Definimos el socket del servidor y el socket del cliente
    ServerSocket echoServer = null;
    Socket clientSocket = null;
    // Definimos la variable para almacenar el nº de conexiones
    int numConnections = 0;
    int port;

    public Server2(int port) {
        this.port = port;
    }

    public void stopServer() {
        System.out.println("Server cleaning up.");
        System.exit(0);
    }

    public void startServer() {
        // Abrimos el socket del servidor. No se pueden definir puertos por
        // debajo de 1024

        try {
            echoServer = new ServerSocket(port);
        } catch (IOException e) {
            System.out.println(e);
        }

        System.out.println("Servidor listo y esperando conexiones de clientes...");

        while (true) {
            try {
                clientSocket = echoServer.accept();
                numConnections++;
                 **// Insert in BD
                 Server2Connection oneconnection = new Server2Connection(clientSocket, numConnections, this);
                 // Generate file and send to client
                 //Server1Connection oneconnection = new Server1Connection(clientSocket, numConnections, this);

                new Thread(oneconnection).start();**

            } catch (IOException e) {
                System.out.println(e);
            }
        }
    }
}

class Server2Connection implements Runnable {
    PrintStream os;
    Socket clientSocket;
    int id;
    Server2 server;
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    Map<DatosAEnviar, DatosAEnviar> datos;

    public Server2Connection(Socket clientSocket, int id, Server2 server) {
        this.clientSocket = clientSocket;
        this.id = id;
        this.server = server;
        System.out.println("Conexión " + id + " establecida en: " + clientSocket);
        System.out.println("Conexión " + id + " establecida por: "
                + clientSocket.getInetAddress());
        try {
            os = new PrintStream(clientSocket.getOutputStream());
            ois = new ObjectInputStream(clientSocket.getInputStream());
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public void run() {
        Connection con;
        Statement smt;
        boolean serverStop = false;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel",
                    "root", "root");

            // Hacemos el cast del stream recibido al tipo de objeto esperado,
            // en este caso un objeto del tipo MapTree
            while ((datos = (Map<DatosAEnviar, DatosAEnviar>) ois.readObject()) != null) {
                for (Entry<DatosAEnviar, DatosAEnviar> itrDatos : datos.entrySet()) {
                    DatosAEnviar clave = itrDatos.getKey();
                    DatosAEnviar valor = itrDatos.getValue();
                    System.out.println(clave + "  ->  " + valor.toString());
                    // Insertamos en la tabla de BBDD cada registro del MapTree
                    // recibido
                    String query = "insert into registro (id_conex, vendedor, ventas, ip_tienda) values( '"
                            + id
                            + "','"
                            + valor.getNombre()
                            + "','"
                            + valor.getVentas()
                            + "','"
                            + clientSocket.getInetAddress().toString().replace("/", "") + "');";
                    smt = con.createStatement();
                    smt.executeUpdate(query);
                }
                // Enviamos al cliente confirmación de que hemos procesado la
                // información correctamente
                os.println("bye");
                break;
            }

            System.out.println("Conexión " + id + " cerrada.");

            // Cerramos la conexión de BBDD
            con.close();
            // Cerramos el canal de entrada
            ois.close();
            // Cerramos el canal de salida
            os.close();
            // Cerramos el socket con el cliente
            clientSocket.close();

            if (serverStop)
                server.stopServer();
        } catch (IOException e) {
            System.out.println(e);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class Server1Connection implements Runnable {
    Socket clientSocket;
    int id;
    Server2 server;
    File myFile = null;
    OutputStream os = null;
    BufferedInputStream bis = null;
    FileInputStream fis = null;

    public Server1Connection(Socket clientSocket, int id, Server2 server) {
        this.clientSocket = clientSocket;
        this.id = id;
        this.server = server;
        System.out.println("Conexión " + id + " establecida en: " + clientSocket);
        try {
            os = clientSocket.getOutputStream();    
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public void run() {

        boolean serverStop = false;
        Connection con;
        Statement smt;
        ResultSet rs;
        try {

            // Conexión a la BBDD
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel","root", "root");
            //Generamos el fichero
            FileWriter writer = new FileWriter("registro_tieda_"+clientSocket.getInetAddress().toString().replace("/", "") + ".txt");
            smt=con.createStatement();
            String query ="SELECT * FROM registro WHERE ip_tienda='" + clientSocket.getInetAddress().toString().replace("/", "") + "';";
            rs = smt.executeQuery(query);
            while(rs.next()) {
                writer.append(rs.getString(3));
                writer.append(';');
                writer.append(rs.getString(4));
                writer.append(';');
                writer.append(rs.getString(5));
                writer.append('\n');                
            }
            writer.close();

            // Enviamos el fichero
              File myFile = new File("registro_tieda_"+clientSocket.getInetAddress().toString().replace("/", "") + ".txt");
              fis = new FileInputStream(myFile);
              bis = new BufferedInputStream(fis);
              byte[] mybytearray = new byte[(int) myFile.length()];
              bis.read(mybytearray, 0, mybytearray.length);
              os.write(mybytearray, 0, mybytearray.length);
              os.flush();
              bis.close();


            // Enviamos al cliente confirmación de que hemos procesado la
            // información correctamente

            System.out.println("Conexión " + id + " cerrada.");

            // Cerramos la conexión de BBDD
            con.close();
            clientSocket.close();
            // Cerramos el fichero


            if (serverStop)
                server.stopServer();
        } catch (IOException e) {
            System.out.println(e);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
}

I have two methods in my code, which one to run depends on if I want to insert in the database or generate a file. Now I have to manually comment out the bold lines.

How can I send from client to server which option to execute? If client arguments are -p I want to execute Server1Connection method, without args Server2Connection method in client program.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Javi
  • 3
  • 2
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Tom Dec 23 '14 at 13:35
  • I dont think so! compare strings? I want the server to run one thread or another function of an input argument client program. – Javi Dec 23 '14 at 13:39
  • Javi, check out this line of your code: `if (args.length != 0 && args[0] == "-p") {`. You can't compare strings like that. You have to use `equals()` in Java. It may not solve your problem, but you should fix it anyway... – AJPerez Dec 23 '14 at 13:42
  • You don't think so? See this `args[0] == "-p"` and read the link again. – Tom Dec 23 '14 at 13:44
  • 1
    @Javi please use English on stack overflow. – Mark Rotteveel Dec 23 '14 at 13:47
  • Sorry tom. You're absolutely right. Fix it! – Javi Dec 23 '14 at 13:48
  • I reverted your last edit because 1) you destroyed my last edits and 2) you 'fixed' your code invalidating all comments already posted. – Mark Rotteveel Dec 23 '14 at 13:49
  • @Javi Due to the wrong comparison, the `if` block will never be entered. So it might cause the problems you have with that code. – Tom Dec 23 '14 at 13:51
  • Sorry. I just wanted to follow the rules. – Javi Dec 23 '14 at 13:52

1 Answers1

0

The problem is that you send nothing to the server to let it know which method to use. You need to establish a protocol, so the client can ask the server for the right action.

You should also only have a single run method in your code which, depending on what the client asks for, performs the right action.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Thks @Mark Rotteveel. This is my problem. How I can do that protocol? How I can tell the server to do one thing or another? – Javi Dec 23 '14 at 13:57
  • You need to send it messages. How you do that exactly is up to you, but you could for example send a string to the server, and let the server decide on the action to perform based on that string. – Mark Rotteveel Dec 23 '14 at 13:59
  • Perfect. Thanks for the help. And I'm sorry for the inconvenience. – Javi Dec 23 '14 at 14:07