miércoles, 1 de febrero de 2012

Comunicaciones UDP III. El Receptor

package es.vaprel.qkandroid.Communications;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.BlockingQueue;

import com.badlogic.gdx.Gdx;

public class ComunicacionesReceptor extends Thread
{ 
 byte [] datosArrayByte;
 InetAddress direccionIp = null; 
 DatagramSocket recepcionSocket;
 DatagramPacket dato;
 private final BlockingQueue colamensajes;
 boolean socetOK = true;
 
 public ComunicacionesReceptor(BlockingQueue colamensajes,InetAddress direccionIp) 
   throws SocketException
 {
  this.direccionIp = direccionIp;
  this.colamensajes = colamensajes;     
  datosArrayByte = new byte[Comunicaciones.PAQUETE_SIZE]; 
  try
  {
   recepcionSocket = new DatagramSocket(Comunicaciones.PUERTO_DONDE_RECIBO);
  }
  catch (IOException ioe)
  {   
   Gdx.app.log("ERROR: ", ioe.getLocalizedMessage(), ioe);
  }      
 } 
 
 @Override
 public void run() {  
  dato = new DatagramPacket(new byte[Comunicaciones.PAQUETE_SIZE], Comunicaciones.PAQUETE_SIZE);
  while (socetOK)
  {
   try
   {
    // BLOQUEANTE
    recepcionSocket.receive(dato);
    // BLOQUEANTE
    ProcesarPaquete(dato);
    if (Thread.interrupted()) {
        try {
      throw new InterruptedException();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
/*
 * By convention, any method that exits by throwing an InterruptedException clears
 *  interrupt status when it does so.
 *  However, it's always possible that interrupt status will immediately be set again,
 *  by another thread invoking interrupt.
 * */
      e.printStackTrace();
      Gdx.app.log("ERROR: ", e.getLocalizedMessage(), e);
      CloseSocket();
     }
    }
   }
   catch(IOException ioe)
   {
    socetOK = false;    
    Gdx.app.log("ERROR: ", ioe.getLocalizedMessage(), ioe);
   }
  }    
 }
 
 //Cuando llega un datagrama lo encola en la cola de mensajes recibidos
 private void ProcesarPaquete(DatagramPacket dato)
 {    
  try
  {
   datosArrayByte = dato.getData();
   Mensaje auxmensaje = new Mensaje(datosArrayByte.toString());
   colamensajes.add(auxmensaje);
  }
  catch (Exception ex)
  {
   Gdx.app.log("ERROR: ", ex.getLocalizedMessage(), ex); 
  }
 }
 
 public void CloseSocket() {
  socetOK = false;
  recepcionSocket.close();    
 }
}

No hay comentarios:

Publicar un comentario