Bressam

ServidorPersistencia - Cliente

Jun 28th, 2018
297
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.99 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package servidorpersistencia;
  7.  
  8. import java.io.IOException;
  9. import java.net.DatagramPacket;
  10. import java.net.InetAddress;
  11. import java.net.MulticastSocket;
  12. import java.net.SocketTimeoutException;
  13. import java.util.Scanner;
  14. import static servidorpersistencia.ServidorPersistencia.IDProcesso;
  15. import static servidorpersistencia.ServidorPersistencia.grupo;
  16. import static servidorpersistencia.ServidorPersistencia.recv;
  17.  
  18. /**
  19.  *
  20.  * @author giovanne.gaspareto
  21.  */
  22. public class Cliente {
  23.    
  24.     static InetAddress              grupo;
  25.     static MulticastSocket          s;
  26.     static DatagramPacket           msg;
  27.     static DatagramPacket           recv;
  28.     private static Scanner          keyboard;
  29.    
  30.     static final String         GROUP_IP = "224.0.0.1";
  31.     static final int            MULTICAST_PORT = 2000;
  32.     static int                  IDProcesso = 0;
  33.     static String               mensagem = "";
  34.     static int                  numeroProcessosGrupo = 0;
  35.     static int                  tempoRandom = 0;
  36.     static int                  idProcessoNaRegiaoCritica = 0;
  37.     static int                  idRecebido = 0;
  38.     static int                  proximo =   0;
  39.     static int                  escolha = 0;
  40.     static String               mensagemTeclado = "";
  41.     static int                  idBusca = 0;
  42.     static boolean              continuarExecucao = true;
  43.     static String               mensagemTecladoEntrada = "";
  44.    
  45.     static final String         CLIENTE_M = "M";
  46.     static final String         DIVISOR_STRING = ";";
  47.     static final String         BUSCA = "b";
  48.     static final String         INSERCAO = "i";
  49.     static final String         RESPOSTA = "resposta";
  50.    
  51.     public static void setUp(){
  52.         try {
  53.             //System.setProperty("java.net.preferIPv4Stack", "true"); // somente pra mac no wifi
  54.             grupo=InetAddress.getByName(GROUP_IP);
  55.             s=new MulticastSocket(MULTICAST_PORT);
  56.             System.err.println("Entrando no grupo ...");
  57.             s.joinGroup(grupo);
  58.             System.err.println("Ok.");
  59.         } catch (IOException e) {
  60.             // TODO Auto-generated catch block
  61.             e.printStackTrace();
  62.         }
  63.     }
  64.    
  65.     public static void defineIDProcesso(){
  66.         keyboard = new Scanner(System.in);
  67.         System.out.println("Informe o ID(i) deste cliente Mi: ");
  68.         IDProcesso = keyboard.nextInt();
  69.     }
  70.    
  71.     public static String receiveMessageGroup(){
  72.         byte[] buf=new byte[1000];
  73.         recv=new DatagramPacket(buf, buf.length);
  74.         try {
  75.             s.setSoTimeout(10);
  76.             s.setLoopbackMode(false);
  77.            // System.out.println("timeout no recevei sem nada: " + s.getSoTimeout());
  78.             s.receive(recv);
  79.             byte[] dest=new byte[recv.getLength()];
  80.             System.arraycopy(recv.getData(), 0, dest, 0, dest.length);
  81.             String mensagemRecebida = new String(recv.getData(),recv.getOffset(),recv.getLength());
  82.          //   System.err.println("Mensagen recebida: "+ mensagemRecebida);
  83.             return mensagemRecebida;
  84.         } catch (SocketTimeoutException ex) {
  85.           // Logger.getLogger(ProcessoSender.class.getName()).log(Level.SEVERE, null, ex);
  86.             return "x;0;0";
  87.         } catch (IOException e) {
  88.             // TODO Auto-generated catch block
  89.             e.printStackTrace();
  90.             return "x;0;0";
  91.         }
  92.     }
  93.    
  94.     public static void sendMessageGroup(String msgStr) {
  95.         msg=new DatagramPacket(msgStr.getBytes(), msgStr.length(),grupo, 2000);
  96.        // System.out.println("Enviando mensagem para o grupo ...");
  97.         try {
  98.             s.send(msg);
  99.         } catch (IOException e) {
  100.             // TODO Auto-generated catch block
  101.             e.printStackTrace();
  102.         }
  103.     }
  104.    
  105.     public static int lerEscolha(){
  106.         keyboard = new Scanner(System.in);
  107.         System.out.println("[Cliente " + IDProcesso+ "]Menu:\n1: Inserir texto \n2: Buscar texto por ID \n3: Desconectar cliente");            
  108.         escolha = keyboard.nextInt();
  109.         return escolha;
  110.     }
  111.    
  112.     public static String lerTeclado(){
  113.         keyboard = new Scanner(System.in);
  114.         System.out.println("Informe o texto a ser enviado: ");
  115.         mensagemTeclado = keyboard.nextLine();
  116.         return mensagemTeclado;
  117.     }
  118.    
  119.     public static int   lerIDBusca(){
  120.         keyboard = new Scanner(System.in);
  121.         System.out.println("Informe o K que sera buscado dentro da base de dados: ");
  122.         escolha = keyboard.nextInt();
  123.         return escolha;
  124.     }
  125.    
  126.     public static void main(String[] args) throws IOException{
  127.        setUp();
  128.        defineIDProcesso();
  129.      //  mensagem = CLIENTE_M+DIVISOR_STRING+IDProcesso;
  130.      // sendMessageGroup(mensagem);
  131.         boolean aguardandoResposta = true;
  132.         String opcao;
  133.         String[] partes = new String[3];
  134.        
  135.        while(continuarExecucao){
  136.        switch(lerEscolha()){
  137.            case 1:
  138.                mensagemTecladoEntrada = lerTeclado();
  139.                mensagem = CLIENTE_M + DIVISOR_STRING + IDProcesso + DIVISOR_STRING + INSERCAO + DIVISOR_STRING +mensagemTecladoEntrada;  // M;1;textoaqui
  140.                sendMessageGroup(mensagem);
  141.                 aguardandoResposta = true;
  142.                while(aguardandoResposta){
  143.                    mensagem = receiveMessageGroup();
  144.                    partes = mensagem.split(DIVISOR_STRING);
  145.                    opcao = partes[0];
  146.                    if(opcao.equals(RESPOSTA)){
  147.                        System.out.println(partes[2]);
  148.                        aguardandoResposta = false;
  149.                    }
  150.                }
  151.                break;
  152.            case 2:
  153.                idBusca = lerIDBusca();
  154.                mensagem = CLIENTE_M + DIVISOR_STRING + IDProcesso + DIVISOR_STRING + BUSCA + DIVISOR_STRING + idBusca;
  155.                sendMessageGroup(mensagem);
  156.                System.out.println(receiveMessageGroup());
  157.                aguardandoResposta = true;
  158.  
  159.                while(aguardandoResposta){
  160.                    mensagem = receiveMessageGroup();
  161.                    partes = mensagem.split(DIVISOR_STRING);
  162.                    opcao = partes[0];
  163.                    if(opcao.equals(RESPOSTA)){
  164.                        System.out.println(partes[2]);
  165.                        aguardandoResposta = false;
  166.                    }
  167.                }
  168.                break;
  169.            case 3:
  170.                 System.err.println("Cliente "+IDProcesso+ " encerrando conexao...");
  171.                 s.leaveGroup(grupo);
  172.                continuarExecucao = false;
  173.             default:
  174.                 System.err.println("Case Default leitura do teclado");
  175.                 break;
  176.             }
  177.        }
  178.        
  179.        
  180.        System.out.println("Cliente desconectado");
  181.        System.exit(0);
  182.     }
  183.    
  184. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment