Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- /**
- *
- * @author luis.tavares
- */
- import java.io.IOException;
- import java.io.InputStream;
- import javax.microedition.io.HttpConnection;
- import javax.microedition.io.ServerSocketConnection;
- import javax.microedition.io.SocketConnection;
- import javax.microedition.io.Connector;
- import SMSHandler;
- import SocketServidorC;
- import SerialHandler;
- public class SocketServidor extends Thread {
- public boolean serverActivo =false;
- public boolean stopServer =false;
- public int lastClient=0;
- public String IPPublic="";
- public String TestData="";
- private ServerSocketConnection server = null;
- private String APNX="";
- private String LoginX="";
- private String PasswordX="";
- private String DNSX="";
- private String portoX="";
- private int numMaxClientsX=1;
- private SocketServidorC client[]=null;
- private boolean blockX=true;
- private boolean debugX=false;
- private int timeoutSocketX=0;
- public String imeiX= null;
- public String chX =null;
- private SerialHandler serialX =null;
- private SMSHandler smsX = null;
- public String ipX = null;
- SocketServidorC socketC;
- SerialHandler serial;
- int flagleitura = 0;
- public SocketServidor (String APN, String Login, String Password,
- String DNS, String porto,int numMaxClients,
- int timeoutSocket, boolean block,boolean debug, String imei, String ch, SerialHandler serial, SMSHandler sms)
- {
- APNX=APN;
- LoginX=Login;
- PasswordX=Password;
- DNSX=DNS;
- portoX=porto;
- numMaxClientsX=numMaxClients;
- blockX=block; //true fará com que o socket client fique bloqueado até receber dados
- timeoutSocketX=timeoutSocket; //=0 O socket nunca se fechara. >0 Se passar estes segundos sem tráfego de entrada gprs o socket fecha
- debugX=debug;
- imeiX=imei;
- chX = ch;
- client=new SocketServidorC[numMaxClientsX];
- serialX = serial;
- smsX = sms;
- }
- //SERVER RUNNING
- public void run()
- {
- int socketLivre=0;
- try
- {
- //O ciclo continua sempre que esta variavel seja falsa
- while (stopServer==false)
- {
- //So o servidor não estiver activo tenta-se abrir
- if (serverActivo==false)
- {
- try
- {
- //Iniciar sessão GPRS e o sockect listener
- // SerialHandler serial = new SerialHandler();
- server = (ServerSocketConnection) Connector.open("socket://:" + portoX + ";bearer_type=GPRS;access_point=" + APNX + ";username="+ LoginX + ";password=" + PasswordX + ";dns=" + DNSX+ ";timeout=0");
- serverActivo=true;
- IPPublic=server.getLocalAddress();
- ipX = IPPublic;
- //Mostrar IP Publico na saída standard de debug
- System.out.println("IP do Controlador:" + IPPublic);
- // Enviar IP do Modem e Imei para Gotraffic
- enviarPost(1);
- if(flagleitura > 0)
- {
- System.out.println(serial.hexch);
- flagleitura=0;
- }
- //Se existir alteração no estado do Semáforo, atualizar GoTraffic
- /* serial.state = false;
- while(serial.state=true);
- {
- enviarPost(10);
- System.out.println("Estado do Semáforo atualizado");
- serial.state = false;
- } */
- //teste
- // enviarPost(10,null);
- // serial.state = false;
- // if( serial.state = true)
- // {
- // enviarPost(10,serial.hex);
- }
- catch (Exception e)
- {
- if (debugX)
- {
- System.out.println("Excepcão SocketServidor run 1");
- System.out.println(e);
- }
- //No caso de erro, fecha-se o server
- closeServer();
- }
- }
- //Se já tiver o servidor activo ...
- else
- {
- try
- {
- //Nos quedamos esperando una conexión una conexión
- SocketConnection sc = (SocketConnection) server.acceptAndOpen();
- TestData=sc.getAddress();
- String iplocal = "87.103.15.209";
- if( TestData.compareTo(iplocal) < 0)
- {
- sc.close();
- }
- //Validar Address (Firewall) // Comparar com IP Local. Se == , open, se não server.close.
- System.out.println("Conexão recebida. IP da máquina:" + TestData);
- //
- //Selecciona um cliente (pode haver numMaxClientsX clientes concurrentes)
- socketLivre=selectClient(lastClient);
- lastClient=socketLivre;
- //Criar e arrancar com um socket
- client[lastClient] = new SocketServidorC(sc,timeoutSocketX,blockX,debugX,imeiX, chX, serialX , smsX , ipX);
- client[lastClient].start();
- }
- //Se salta para a excepção fecha-se tudo
- catch (Exception e)
- {
- if (debugX)
- {
- System.out.println("Excepção no SocketServidor run 2");
- System.out.println(e);
- }
- closeServer();
- }
- }
- }
- }
- //Se salta para a excepção fecha-se tudo
- catch (Exception e)
- {
- if (debugX)
- {
- System.out.println("Excepção no SocketServidor run 3");
- System.out.println(e);
- }
- closeServer();
- }
- }
- // Método para enviar para o site
- void enviarPost(int i)throws IOException{
- System.out.println("Estabelecendo contacto com gotraffic.soltrafego.pt...");
- HttpConnection connection = null;
- InputStream inputstream_ = null;
- String url = null;
- StringBuffer dataReceived = null;
- if(i == 1)
- {
- url = "http://gotraffic.soltrafego.pt/index.php?IMEI=" + imeiX + "&IP=" + ipX;
- }
- //53543D303B44723D4E616F
- else
- {
- url = "http://gotraffic.soltrafego.pt/index.php?data={IMEI:"+ imeiX +",TS:20/04/13%2008:31:44,SER:"+ serial.hexch +"}";
- // url = "http://gotraffic.soltrafego.pt/index.php?data={IMEI="+ imeiX + ",TS:15/11/15%2008:08:31:44,SER:" + serialX.hexch + "}";
- System.out.println(url);
- //serialX.hex
- // url = "http://gotraffic.soltrafego.pt/index.php?data={\"IMEI=\":\"1234567890001\",\"TS\":\"19/11/15%2008:08:31:44\",\"SER\":\"53543D313B44723D4E616F\"}";
- }
- dataReceived = new StringBuffer();
- try {
- connection = (HttpConnection) Connector.open(url);
- connection.setRequestMethod(HttpConnection.GET);
- connection.setRequestProperty("Content-Type", "text/plain");
- connection.setRequestProperty("Connection", "close");
- if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
- inputstream_ = connection.openInputStream();
- int ch;
- while ((ch = inputstream_.read()) != -1 ) {
- dataReceived.append((char) ch);
- }
- } else {
- // Connection not ok
- }
- } catch (Exception e) {
- // Something went wrong
- } finally {
- if (inputstream_ != null) {
- try {
- System.out.println("Atualizado.");
- // inputstream_.close();
- } catch (Exception e) {
- }
- }
- if (connection != null) {
- try {
- connection.close();
- } catch (Exception e) {
- }
- }
- }
- }
- //Método para fechar o servidor
- public void closeServer()
- {
- try
- {
- stopServer=true;
- serverActivo=false;
- server.close();
- }
- catch (Exception e)
- {
- if (debugX)
- {
- System.out.println("Excepção no SocketServidor closeServer");
- System.out.println(e);
- }
- }
- }
- //Verifica se um cliente está activo ou não
- private int selectClient(int lastClient)
- {
- int i=0;
- try
- {
- //Procura um cliente livre
- for (i=0;i<numMaxClientsX;i++)
- {
- if (isClienteActivo(client[i])==false)
- return i;
- }
- //Se não houver ninguem livre, considera-se um, forzando o encerramento do último socket
- lastClient=(lastClient+1)%numMaxClientsX;
- client[lastClient].activo=false;
- client[lastClient].interrupt();
- client[lastClient].join();
- return lastClient;
- }
- catch (Exception e)
- {
- if (debugX)
- {
- System.out.println("Excepção no SocketServidor selectClient");
- System.out.println(e);
- }
- return 0;
- }
- }
- //Verifica se um socket está activo ou não
- private boolean isClienteActivo(SocketServidorC socket)
- {
- try
- {
- if (socket.activo==true)
- return true;
- else
- return false;
- }
- catch (Exception e)
- {
- if (debugX)
- {
- System.out.println("Excepção no SocketServidor isClienteActivo");
- System.out.println(e);
- }
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement