Socket/Threads (Client / Server) Java

I have a very cruel doubt.I researched a lot and didn't find anything like it to solve my case.

What I need is this:

  • The customer side sends card number and purchase value

  • The server side receives this data and queries 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 inform the password of the card.

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

Can anyone give me an idea of how to do this or do they have any examples like 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
   }
}
Author: ramaral, 2016-03-15

1 answers

I did an exercise of these late last year. You are not specifying whether you can have multiple clients connected at the same time, but whether you do. Can from the server an extension for 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();
        }
    }
}
 0
Author: Brumazzi DB, 2016-03-15 20:17:52