Guest User

Untitled

a guest
Oct 25th, 2016
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.71 KB | None | 0 0
  1.  
  2.  
  3. /*
  4.  * To change this template, choose Tools | Templates
  5.  * and open the template in the editor.
  6.  */
  7.  
  8. /**
  9.  *
  10.  * @author luis.tavares
  11.  */
  12.  
  13. import javax.microedition.io.ServerSocketConnection;
  14. import javax.microedition.io.SocketConnection;
  15. import javax.microedition.io.Connector;
  16. import SMSHandler;
  17. import SocketServidorC;
  18.  
  19.  
  20.  
  21. public class SocketServidor extends Thread {
  22.     public boolean serverActivo =false;
  23.     public boolean stopServer =false;
  24.     public int lastClient=0;
  25.     public String IPPublic="";
  26.    
  27.     public String TestData="";
  28.    
  29.     private ServerSocketConnection server = null;
  30.     private String APNX="";
  31.     private String LoginX="";
  32.     private String PasswordX="";
  33.     private String DNSX="";
  34.     private String portoX="";
  35.     private int numMaxClientsX=1;
  36.     private SocketServidorC client[]=null;
  37.     private boolean blockX=true;
  38.     private boolean debugX=false;
  39.     private int timeoutSocketX=0;
  40.     public String imeiX= null;
  41.     public String chX =null;
  42.     private SerialHandler serialX =null;
  43.     private SMSHandler smsX = null;
  44.     public String ipX = null;
  45.  
  46.    
  47.    
  48.     public SocketServidor (String APN, String Login, String Password,
  49.         String DNS, String porto,int numMaxClients,
  50.         int timeoutSocket, boolean block,boolean debug, String imei, String ch, SerialHandler serial, SMSHandler sms)
  51.     {
  52.         APNX=APN;
  53.         LoginX=Login;
  54.         PasswordX=Password;
  55.         DNSX=DNS;  
  56.         portoX=porto;
  57.         numMaxClientsX=numMaxClients;
  58.         blockX=block;               //true fará com que o socket client fique bloqueado até receber dados
  59.         timeoutSocketX=timeoutSocket;   //=0 O socket nunca se fechara. >0 Se passar estes segundos sem tráfego de entrada gprs o socket fecha
  60.         debugX=debug;
  61.         imeiX=imei;
  62.         chX = ch;
  63.         client=new SocketServidorC[numMaxClientsX];
  64.         serialX = serial;
  65.         smsX = sms;
  66.     }
  67.    
  68.    
  69.     //SERVER RUNNING
  70.     public void run()
  71.     {
  72.         int socketLivre=0;
  73.        
  74.         try
  75.         {
  76.             //O ciclo continua sempre que esta variavel seja falsa
  77.             while (stopServer==false)
  78.             {
  79.                 //So o servidor não estiver activo tenta-se abrir
  80.                 if (serverActivo==false)
  81.                 {
  82.                     try
  83.                     {  
  84.                         //Iniciar sessão GPRS e o sockect listener
  85.             //          SerialHandler serial = new SerialHandler();
  86.                         server = (ServerSocketConnection) Connector.open("socket://:" + portoX + ";bearer_type=GPRS;access_point=" + APNX + ";username="+ LoginX + ";password=" + PasswordX + ";dns=" + DNSX+ ";timeout=0");
  87.                         serverActivo=true;                 
  88.                         IPPublic=server.getLocalAddress();
  89.                         ipX = IPPublic;
  90.                
  91.                         //Mostrar IP Publico na saída standard de debug
  92.                         System.out.println("IP:" + IPPublic);
  93.                        
  94.                        
  95.                    
  96.                    
  97.                     }
  98.                     catch (Exception e)
  99.                     {
  100.                         if (debugX)
  101.                         {
  102.                             System.out.println("Excepcão SocketServidor run 1");
  103.                             System.out.println(e);
  104.                         }
  105.                         //No caso de erro, fecha-se o server
  106.                         closeServer();
  107.                     }
  108.                 }
  109.                 //Se já tiver o servidor activo ...
  110.                 else
  111.                 {
  112.                     try
  113.                     {                  
  114.                         //Nos quedamos esperando una conexión una conexión
  115.                        
  116.                         SocketConnection sc = (SocketConnection) server.acceptAndOpen();   
  117.                        
  118.                        
  119.                        
  120.                        
  121.                         TestData=sc.getAddress();
  122.                         String iplocal = "87.103.15.209";
  123.                         if( TestData.compareTo(iplocal) < 0)
  124.                         {
  125.                             sc.close();
  126.                         }
  127.                        
  128.                         //Validar Address (Firewall) // Comparar com IP Local. Se == , open, se não server.close.
  129.                         System.out.println("HOST CONNECTED:" + TestData);
  130.                        
  131.                        
  132.                         //
  133.                        
  134.                        
  135.                         //Selecciona um cliente (pode haver numMaxClientsX clientes concurrentes)
  136.                         socketLivre=selectClient(lastClient);
  137.                         lastClient=socketLivre;
  138.                         //Criar e arrancar com um socket
  139.                         client[lastClient] = new SocketServidorC(sc,timeoutSocketX,blockX,debugX,imeiX, chX, serialX , smsX , ipX);
  140.                         client[lastClient].start();
  141.                        
  142.                     }
  143.                     //Se salta para a excepção fecha-se tudo
  144.                     catch (Exception e)
  145.                     {
  146.                         if (debugX)
  147.                         {
  148.                             System.out.println("Excepção no SocketServidor run 2");
  149.                             System.out.println(e);
  150.                         }
  151.                         closeServer();
  152.                     }
  153.                 }
  154.  
  155.                
  156.             }
  157.  
  158.         }
  159.         //Se salta para a excepção fecha-se tudo
  160.         catch (Exception e)
  161.         {
  162.             if (debugX)
  163.             {
  164.                 System.out.println("Excepção no SocketServidor run 3");
  165.                 System.out.println(e);
  166.             }      
  167.             closeServer();
  168.         }
  169.     }
  170.    
  171.  
  172.  
  173.    
  174.     //Método para fechar o servidor
  175.     public void closeServer()
  176.     {
  177.         try
  178.         {
  179.             stopServer=true;
  180.             serverActivo=false;
  181.             server.close();
  182.         }
  183.         catch (Exception e)
  184.         {
  185.             if (debugX)
  186.             {
  187.                 System.out.println("Excepção no SocketServidor closeServer");
  188.                 System.out.println(e);
  189.             }
  190.         }
  191.     }  
  192.    
  193.    
  194.    
  195.    
  196.     //Verifica se um cliente está activo ou não
  197.     private int selectClient(int lastClient)
  198.     {
  199.         int i=0;
  200.         try
  201.         {
  202.             //Procura um cliente livre
  203.             for (i=0;i<numMaxClientsX;i++)
  204.             {
  205.                 if (isClienteActivo(client[i])==false)
  206.                     return i;
  207.             }
  208.             //Se não houver ninguem livre, considera-se um, forzando o encerramento do último socket
  209.             lastClient=(lastClient+1)%numMaxClientsX;
  210.             client[lastClient].activo=false;
  211.             client[lastClient].interrupt();
  212.             client[lastClient].join();
  213.        
  214.             return lastClient;
  215.         }
  216.         catch (Exception e)
  217.         {
  218.             if (debugX)
  219.             {
  220.                 System.out.println("Excepção no SocketServidor selectClient");
  221.                 System.out.println(e);
  222.             }          
  223.             return 0;
  224.         }      
  225.     }
  226.    
  227.    
  228.     //Verifica se um socket está activo ou não
  229.     private boolean isClienteActivo(SocketServidorC socket)
  230.     {
  231.         try
  232.         {
  233.             if (socket.activo==true)
  234.                 return true;
  235.             else
  236.                 return false;
  237.         }
  238.         catch (Exception e)
  239.         {
  240.             if (debugX)
  241.             {
  242.                 System.out.println("Excepção no SocketServidor isClienteActivo");
  243.                 System.out.println(e);
  244.             }          
  245.             return false;
  246.         }      
  247.     }
  248.  
  249.  
  250.  
  251.  
  252.  
  253.  
  254.  
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261. }
Add Comment
Please, Sign In to add comment