Artigos
Java
Como fazer um ping em conexões de rede nos dispositivos J2ME
Como fazer um ping em conexões de rede nos dispositivos J2ME
A ilustração abaixo dá um ping no servidor com um intervalo de 1 minuto.
|
import java.io.*; import javax.microedition.midlet.*; import javax.microedition.io.*; import javax.microedition.lcdui.*;
public class pingMIDLET extends MIDlet { private Display display; private String url = "http://server"; private Form form; private Command exit; private Command stop; private Timer timer; private RunTimerTask tt; private int count = 0; boolean isPing = false; public pingMIDLET() { display = Display.getDisplay(this); form = new Form("Ping"); exit = new Command("Exit", Command.EXIT, 1); stop= new Command("Parar", Command.STOP, 2); } public void startApp() { form.addCommand(exit); form.addCommand(stop); form.setCommandListener(this); // Repetindo a cada 1 minuto timer = new Timer(); tt = new RunTimerTask(); timer.schedule(tt,0, 1000*60); if(isPing) { timer.cancel(); } display.setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable d) { if (c == stop) { timer.cancel(); } else if (c == exit) { destroyApp(false); notifyDestroyed(); } } /*-------------------------------------------------- * Classe RunTimerTask – Executando a tarefa *-------------------------------------------------*/ private class RunTimerTask extends TimerTask { public final void run() { HttpConnection c = null; OutputStream os = null; InputStream is = null; int ch; StringBuffer b = new StringBuffer(); try { c = (HttpConnection)Connector.open(url); // Configurando o request method e cabeçalhos c.setRequestMethod(HttpConnection.POST); c.setRequestProperty( "If-Modified-Since","7 Sep 2005 19:43:31 GMT"); c.setRequestProperty( "User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0"); c.setRequestProperty("Content-Language", "en-US"); // Otendo a saída os = c.openOutputStream(); os.write("Ping".getBytes()); os.flush(); is = c.openInputStream(); while ((ch = is.read()) != -1) { b.append((char)ch); } isPing = true; form.append("ping - Sucesso"); } catch(IOException e) { isPing = false; form.append("Pinging....."); } finally { is.close(); os.close(); c.close(); } } } } |