Java - Decrementar y Aumentar, con Socket

 
Vista:
sin imagen de perfil
Val: 6
Ha aumentado su posición en 3 puestos en Java (en relación al último mes)
Gráfica de Java

Decrementar y Aumentar, con Socket

Publicado por Valeria (2 intervenciones) el 09/02/2021 16:26:35
Buenas tardes,

He programado un cliente /servidor.

El caso es que en la paso de información me piden en el JFrame del cliente que pueda enviar, aumentar y decrementar el stock de un producto. Enviar lo tengo pero lo demás no.

En el caso del JFrame del servidor me pide que tenga un botón que pueda consultar el Stock.

Me he quedado bloqueada porque no se como relacionar el Stock de un producto dentro de los sockets, si tiene que ser otra clase o simplemente una variable que se va guardando.

En los métodos enviar se le pasa ya un parámetro, pero este único y no se queda guardado. He creado una clase chirimoya, pero me he quedado igual

Os dejo el código:
Cliente

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public T3_hilocliente(javax.swing.JTextArea txtArea){
          try{
 
              //Conectamos al socket del cliente con el servidor y el puerto
              cliente = new Socket (SERVER, PUERTO);
               this.txtArea=txtArea;
              this.txtArea.append("Hilo Creado"+"\n"+"PSP-TAREA INDIVIDUAL 4- CLIENTE/SERVIDOR"+"\n"+"Valeria de la Rubia, 31029734C"+ System.lineSeparator());
 
              enviar = new PrintWriter (cliente.getOutputStream(),true);
              recibir = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
 
 
 
          }catch(Exception ex){
              this.txtArea.append("Error al iniciar"+ ex.getMessage()+System.lineSeparator());
 
          }
      }
       public void enviar (String chirimoyas){
 
        enviar.println ();
        enviar.flush();
    }
      public void retirar ( int chirimoyas){
          enviar.println(chirimoyas --);
          enviar.flush();
      }
 
      public void comprar( int chirimoyas){
          int resultado=chirimoyas + chirimoyas;
          enviar.println(resultado);
          enviar.flush();
 
      }
 
        public void run (){
      try{ this.txtArea.append("CLIENTE EN ESPERA... " + System.lineSeparator());
            String comando =recibir.readLine();
 
        while (!salir ){
 
            comando =recibir.readLine();
 
            this.txtArea.append("SERVIDOR: " + comando + System.lineSeparator());
        }
 
      }
      catch (Exception ex){
            this.txtArea.append("ERROR EN EL CLIENTE: " + ex.getMessage()+ System.lineSeparator());
 
      }
 
    }
 
}

Mis dudas son como pongo el objeto y como programo en los botones, porque el boton enviar funciona pero el número se va actualizando, no sumando.

El botón de enviar se queda así:

1
h.enviar(txtenviar.getText());
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Decrementar y Aumentar, con Socket

Publicado por Tom (1831 intervenciones) el 10/02/2021 12:44:50
No parece que tengas nada claro lo que hacer ...
Dejo un ejemplo (porque me parece divertido) de cómo haría yo algo así.
Se trata de un único proyecto con 3 paquetes (common, server, client). El punto de entrada del server es la clase InventoryServer y el del cliente ... InventoryClient.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package client;
import common.InventoryIface;
import common.ProductIface;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
/**
 *
 * @author Tom
 */
public class InventoryClient {
	private static ProductIface prods[];
	/* */
	public static void main(String[] args) {
		try {
			Registry reg = LocateRegistry.getRegistry("127.0.0.1", 8181);
			InventoryIface mir = (InventoryIface)reg.lookup("Inventory");
			prods = mir.getProducts();
			listProds();
			for(ProductIface p : prods) {
				p.setInventory(20);
				p.incInventory(-5);
			}
			listProds();
 
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	/* */
	public static void listProds() throws RemoteException {
		System.out.println("Products:");
		for(ProductIface p : prods) {
			System.out.printf("  %s : %d\n", p.getName(), p.getInventory());
		}
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package server;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
/**
 *
 * @author Tom
 */
public class InventoryServer {
	public static void main(String[] args) {
		try {
			Inventory inv = new Inventory();
 
			inv.add(new Product("Apple"));
			inv.add(new Product("Orange"));
 
			Registry reg = LocateRegistry.createRegistry(8181);
 
			reg.rebind("Inventory", inv);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package server;
import common.InventoryIface;
import common.ProductIface;
import java.rmi.RemoteException;
import java.util.ArrayList;
/**
 *
 * @author Tom
 */
public class Inventory extends java.rmi.server.UnicastRemoteObject implements InventoryIface {
	private ArrayList<Product> products;
	/* */
	public Inventory() throws RemoteException {
		products = new ArrayList<>();
	}
	/* */
	public void add(Product p) {
		products.add(p);
	}
	@Override
	public ProductIface[] getProducts() throws RemoteException {
		return products.toArray(new ProductIface[0]);
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package server;
import java.rmi.RemoteException;
import common.ProductIface;
/**
 *
 * @author Tom
 */
public class Product extends java.rmi.server.UnicastRemoteObject implements ProductIface {
	String name;
	int total;
	/* */
	public Product(String name) throws java.rmi.RemoteException {
		super();
		this.name = name;
		total = 0;
	}
	@Override
	public void setInventory(int total) throws RemoteException {
		this.total = total;
	}
	@Override
	public void incInventory(int partial) throws RemoteException {
		total += partial;
	}
	@Override
	public int getInventory() throws RemoteException {
		return total;
	}
	@Override
	public String getName() throws RemoteException {
		return name;
	}
}

1
2
3
4
5
6
7
8
9
package common;
 
/**
 *
 * @author Tom
 */
public interface InventoryIface extends java.rmi.Remote {
	public ProductIface[] getProducts() throws java.rmi.RemoteException;
}

1
2
3
4
5
6
7
8
9
10
11
12
package common;
 
/**
 *
 * @author Tom
 */
public interface ProductIface extends java.rmi.Remote {
	public void setInventory(int total) throws java.rmi.RemoteException;
	public void incInventory(int partial) throws java.rmi.RemoteException;
	public String getName() throws java.rmi.RemoteException;
	public int getInventory() throws java.rmi.RemoteException;
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
sin imagen de perfil
Val: 6
Ha aumentado su posición en 3 puestos en Java (en relación al último mes)
Gráfica de Java

Decrementar y Aumentar, con Socket

Publicado por Valeria (2 intervenciones) el 10/02/2021 14:49:25
Muchas gracias por la aportación.
No conocía estas bibliotecas
1
2
import common.InventoryIface;
import common.ProductIface;

Sin embargo, lo que busco es como decrementar o incrementar el producto desde un botón personalizado.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar