Advertisement
Guest User

SocketServidor_271016

a guest
Oct 27th, 2016
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.96 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 java.io.IOException;
  14. import java.io.InputStream;
  15.  
  16. import javax.microedition.io.HttpConnection;
  17. import javax.microedition.io.ServerSocketConnection;
  18. import javax.microedition.io.SocketConnection;
  19. import javax.microedition.io.Connector;
  20. import SMSHandler;
  21. import SocketServidorC;
  22. import SerialHandler;
  23.  
  24.  
  25. public class SocketServidor extends Thread {
  26. public boolean serverActivo =false;
  27. public boolean stopServer =false;
  28. public int lastClient=0;
  29. public String IPPublic="";
  30.  
  31. public String TestData="";
  32.  
  33. private ServerSocketConnection server = null;
  34. private String APNX="";
  35. private String LoginX="";
  36. private String PasswordX="";
  37. private String DNSX="";
  38. private String portoX="";
  39. private int numMaxClientsX=1;
  40. private SocketServidorC client[]=null;
  41. private boolean blockX=true;
  42. private boolean debugX=false;
  43. private int timeoutSocketX=0;
  44. public String imeiX= null;
  45. public String chX =null;
  46. private SerialHandler serialX =null;
  47. private SMSHandler smsX = null;
  48. public String ipX = null;
  49. SocketServidorC socketC;
  50. SerialHandler serial;
  51. int flagleitura = 0;
  52.  
  53.  
  54. public SocketServidor (String APN, String Login, String Password,
  55. String DNS, String porto,int numMaxClients,
  56. int timeoutSocket, boolean block,boolean debug, String imei, String ch, SerialHandler serial, SMSHandler sms)
  57. {
  58. APNX=APN;
  59. LoginX=Login;
  60. PasswordX=Password;
  61. DNSX=DNS;
  62. portoX=porto;
  63. numMaxClientsX=numMaxClients;
  64. blockX=block; //true fará com que o socket client fique bloqueado até receber dados
  65. timeoutSocketX=timeoutSocket; //=0 O socket nunca se fechara. >0 Se passar estes segundos sem tráfego de entrada gprs o socket fecha
  66. debugX=debug;
  67. imeiX=imei;
  68. chX = ch;
  69. client=new SocketServidorC[numMaxClientsX];
  70. serialX = serial;
  71. smsX = sms;
  72.  
  73. }
  74.  
  75.  
  76. //SERVER RUNNING
  77. public void run()
  78. {
  79. int socketLivre=0;
  80.  
  81. try
  82. {
  83. //O ciclo continua sempre que esta variavel seja falsa
  84. while (stopServer==false)
  85. {
  86. //So o servidor não estiver activo tenta-se abrir
  87. if (serverActivo==false)
  88. {
  89. try
  90. {
  91. //Iniciar sessão GPRS e o sockect listener
  92. // SerialHandler serial = new SerialHandler();
  93. server = (ServerSocketConnection) Connector.open("socket://:" + portoX + ";bearer_type=GPRS;access_point=" + APNX + ";username="+ LoginX + ";password=" + PasswordX + ";dns=" + DNSX+ ";timeout=0");
  94. serverActivo=true;
  95. IPPublic=server.getLocalAddress();
  96. ipX = IPPublic;
  97.  
  98. //Mostrar IP Publico na saída standard de debug
  99. System.out.println("IP do Controlador:" + IPPublic);
  100. // Enviar IP do Modem e Imei para Gotraffic
  101.  
  102. enviarPost(1);
  103. if(flagleitura > 0)
  104. {
  105. System.out.println(serial.hexch);
  106. flagleitura=0;
  107. }
  108. //Se existir alteração no estado do Semáforo, atualizar GoTraffic
  109. /* serial.state = false;
  110.  
  111.  
  112. while(serial.state=true);
  113. {
  114. enviarPost(10);
  115. System.out.println("Estado do Semáforo atualizado");
  116. serial.state = false;
  117. } */
  118.  
  119.  
  120. //teste
  121.  
  122. // enviarPost(10,null);
  123.  
  124.  
  125.  
  126. // serial.state = false;
  127. // if( serial.state = true)
  128. // {
  129. // enviarPost(10,serial.hex);
  130.  
  131. }
  132.  
  133.  
  134. catch (Exception e)
  135. {
  136. if (debugX)
  137. {
  138. System.out.println("Excepcão SocketServidor run 1");
  139. System.out.println(e);
  140. }
  141. //No caso de erro, fecha-se o server
  142. closeServer();
  143.  
  144. }
  145.  
  146.  
  147. }
  148.  
  149.  
  150. //Se já tiver o servidor activo ...
  151. else
  152. {
  153. try
  154. {
  155. //Nos quedamos esperando una conexión una conexión
  156.  
  157. SocketConnection sc = (SocketConnection) server.acceptAndOpen();
  158.  
  159.  
  160.  
  161.  
  162. TestData=sc.getAddress();
  163. String iplocal = "87.103.15.209";
  164. if( TestData.compareTo(iplocal) < 0)
  165. {
  166. sc.close();
  167. }
  168.  
  169. //Validar Address (Firewall) // Comparar com IP Local. Se == , open, se não server.close.
  170. System.out.println("Conexão recebida. IP da máquina:" + TestData);
  171.  
  172.  
  173. //
  174.  
  175.  
  176. //Selecciona um cliente (pode haver numMaxClientsX clientes concurrentes)
  177. socketLivre=selectClient(lastClient);
  178. lastClient=socketLivre;
  179. //Criar e arrancar com um socket
  180. client[lastClient] = new SocketServidorC(sc,timeoutSocketX,blockX,debugX,imeiX, chX, serialX , smsX , ipX);
  181. client[lastClient].start();
  182.  
  183. }
  184. //Se salta para a excepção fecha-se tudo
  185. catch (Exception e)
  186. {
  187. if (debugX)
  188. {
  189. System.out.println("Excepção no SocketServidor run 2");
  190. System.out.println(e);
  191. }
  192. closeServer();
  193. }
  194. }
  195.  
  196.  
  197. }
  198.  
  199. }
  200. //Se salta para a excepção fecha-se tudo
  201. catch (Exception e)
  202. {
  203. if (debugX)
  204. {
  205. System.out.println("Excepção no SocketServidor run 3");
  206. System.out.println(e);
  207. }
  208. closeServer();
  209. }
  210. }
  211.  
  212. // Método para enviar para o site
  213. void enviarPost(int i)throws IOException{
  214.  
  215. System.out.println("Estabelecendo contacto com gotraffic.soltrafego.pt...");
  216. HttpConnection connection = null;
  217. InputStream inputstream_ = null;
  218. String url = null;
  219. StringBuffer dataReceived = null;
  220. if(i == 1)
  221. {
  222. url = "http://gotraffic.soltrafego.pt/index.php?IMEI=" + imeiX + "&IP=" + ipX;
  223. }
  224. //53543D303B44723D4E616F
  225. else
  226. {
  227. url = "http://gotraffic.soltrafego.pt/index.php?data={IMEI:"+ imeiX +",TS:20/04/13%2008:31:44,SER:"+ serial.hexch +"}";
  228. // url = "http://gotraffic.soltrafego.pt/index.php?data={IMEI="+ imeiX + ",TS:15/11/15%2008:08:31:44,SER:" + serialX.hexch + "}";
  229. System.out.println(url);
  230. //serialX.hex
  231. // url = "http://gotraffic.soltrafego.pt/index.php?data={\"IMEI=\":\"1234567890001\",\"TS\":\"19/11/15%2008:08:31:44\",\"SER\":\"53543D313B44723D4E616F\"}";
  232.  
  233. }
  234.  
  235. dataReceived = new StringBuffer();
  236.  
  237. try {
  238.  
  239. connection = (HttpConnection) Connector.open(url);
  240.  
  241. connection.setRequestMethod(HttpConnection.GET);
  242.  
  243. connection.setRequestProperty("Content-Type", "text/plain");
  244. connection.setRequestProperty("Connection", "close");
  245.  
  246. if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
  247. inputstream_ = connection.openInputStream();
  248. int ch;
  249.  
  250. while ((ch = inputstream_.read()) != -1 ) {
  251. dataReceived.append((char) ch);
  252.  
  253. }
  254. } else {
  255. // Connection not ok
  256. }
  257. } catch (Exception e) {
  258. // Something went wrong
  259. } finally {
  260. if (inputstream_ != null) {
  261. try {
  262. System.out.println("Atualizado.");
  263. // inputstream_.close();
  264. } catch (Exception e) {
  265. }
  266. }
  267. if (connection != null) {
  268. try {
  269. connection.close();
  270. } catch (Exception e) {
  271. }
  272. }
  273. }
  274. }
  275.  
  276.  
  277. //Método para fechar o servidor
  278. public void closeServer()
  279. {
  280. try
  281. {
  282. stopServer=true;
  283. serverActivo=false;
  284. server.close();
  285. }
  286. catch (Exception e)
  287. {
  288. if (debugX)
  289. {
  290. System.out.println("Excepção no SocketServidor closeServer");
  291. System.out.println(e);
  292. }
  293. }
  294. }
  295.  
  296.  
  297.  
  298.  
  299. //Verifica se um cliente está activo ou não
  300. private int selectClient(int lastClient)
  301. {
  302. int i=0;
  303. try
  304. {
  305. //Procura um cliente livre
  306. for (i=0;i<numMaxClientsX;i++)
  307. {
  308. if (isClienteActivo(client[i])==false)
  309. return i;
  310. }
  311. //Se não houver ninguem livre, considera-se um, forzando o encerramento do último socket
  312. lastClient=(lastClient+1)%numMaxClientsX;
  313. client[lastClient].activo=false;
  314. client[lastClient].interrupt();
  315. client[lastClient].join();
  316.  
  317. return lastClient;
  318. }
  319. catch (Exception e)
  320. {
  321. if (debugX)
  322. {
  323. System.out.println("Excepção no SocketServidor selectClient");
  324. System.out.println(e);
  325. }
  326. return 0;
  327. }
  328. }
  329.  
  330.  
  331. //Verifica se um socket está activo ou não
  332. private boolean isClienteActivo(SocketServidorC socket)
  333. {
  334. try
  335. {
  336. if (socket.activo==true)
  337. return true;
  338. else
  339. return false;
  340. }
  341. catch (Exception e)
  342. {
  343. if (debugX)
  344. {
  345. System.out.println("Excepção no SocketServidor isClienteActivo");
  346. System.out.println(e);
  347. }
  348. return false;
  349. }
  350. }
  351.  
  352.  
  353.  
  354.  
  355.  
  356.  
  357.  
  358.  
  359.  
  360.  
  361.  
  362.  
  363.  
  364. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement