Socket/Threads (Client/Server) Java

Asked

Viewed 2,375 times

0

I have a very cruel doubt. I did a lot of research and found nothing similar to solve my case.

What I need is this:

  • Customer side sends card number and purchase value

  • The server side receives this data and queries in the database if the number exists and if the balance is sufficient.

  • If it is ok the Server side sends to the Client message to enter the card password.

  • The server again receives the information and queries the database if the password is ok and returns the error or success message.

Can someone give me an idea of how to do this or has some example similar to this ?

Server :

public class Servidor extends Thread{
  private Socket socket; //O socket da conexão com o cliente

  public Servidor(Socket socket)
  {
    this.socket = socket;
  }

  @Override
  public void run()
  {
    try
    {
      //Obtém os streams de entrada e saída
      DataInputStream in = new DataInputStream(socket.getInputStream());
      DataOutputStream out = new DataOutputStream(socket.getOutputStream());

      double cartao = in.readDouble(); 
      double valor = in.readDouble(); 

    }
    catch (IOException ex)
    {
      System.err.println("Erro: " + ex.getMessage());
    }

  }
}

Main (Server)

public class Main
{
   public static void main(String [] args)
   {
     try
     {
       ServerSocket serverSocket = new ServerSocket(12345); //Cria um server socket para aguardar requisições dos clientes
       while(true)
       {
         System.out.println("Aguardando conexões...");
         Socket socket = serverSocket.accept(); //Fica aguardando pedidos de conexão
         System.out.println("Conectou-se...");
         (new Servidor(socket)).start(); //Inicia a thread que tratará do cliente
       }
     }
     catch (IOException ex)
     {
       System.err.println("Erro: " + ex.getMessage());
     }
   }
}

Client :

public class Cliente extends Thread
{
  private String ip; //O IP do servidor
  private int porta; //A porta de comunicação que será utilizada

  public Cliente(String ip, int porta)
  {
    this.ip = ip;
    this.porta = porta;
  }

  @Override
  public void run()
  {
    try
    {
      System.out.println("** Pagamento On Line **");
      Scanner input = new Scanner(System.in);
      System.out.print("Informe o numero do cartão: ");
      double cartao = input.nextDouble(); 
      System.out.print("Informe o valor da compra: ");
      double valor = input.nextDouble(); 

      Socket socket = new Socket(ip, porta); //Conecta-se ao servidor
      //Obtém os streams de entrada e saída
      DataInputStream in = new DataInputStream(socket.getInputStream());
      DataOutputStream out = new DataOutputStream(socket.getOutputStream());
      out.writeDouble(cartao); 
      out.flush(); //Força o envio

      out.writeDouble(valor); 
      out.flush();

    }
    catch (Exception ex)
    {
      System.err.println("Erro: " + ex.getMessage());
    }
  }
} 

Main (Client)

public class Main
{
   public static void main(String [] args)
   {
      //Cria o cliente para se conectar ao servidor no IP 127.0.0.1 e porta 12345
      Cliente cliente = new Cliente("127.0.0.1", 12345);
      cliente.start(); //Coloca a thread do cliente para ser executada
   }
}

1 answer

0


I did an exercise like this last year. You’re not specifying whether you can have multiple clients connected at the same time, but if you have. An extension to the thread.

public class Server{

    public static void main(String args[]){
        ServerSocket ss = new ServerSocket(12345);
        Socket cli = null;

        // sempre que um novo cliente se conectar ao
        // sistema, uma nova thread será criada
        while(1){
            boolean on = true;
            cli = ss.accept();

            while(on){
                /*Entradas, Saídas e condições dentro do while*/
                /*...*/
            }
            cli.close();
        }
    }
}
  • Ola Brumazzi, it is not necessary to have multiple customers at the same time.

  • made the change to a user. if it is not very explanatory of a look at this link: https://github.com/brumazzi/Sistema_Bancario

  • Brumazzi, I’ll take a look later and give you a feedback. Thank you so much for the help man.

  • Brumazzi D.B. your system got ball show, helped me a lot to understand the processes between client/server. Thank you very much.

  • I had to focus on readability because I had to explain the code, kkkkkkkk

  • It was amazing guy, very didactic. Congratulations and thanks again.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.