Tuesday, April 19, 2011

Ajax long connect using server heart beat to check client connect if it is closed

Using a trick HTTP response header

HTTP/1.1 200 OK
Server: xxx
Beat: Waiting.................................... // trick
Connection:Close
Content-length:255
Content-type:text/xml
Date:Wed Apr 20 12:01:17 EST 2011
Expires:Sun, 24 Apr 1981 01:29:32 GMT




//PrintStream ps; - Java socket output stream
private boolean waitForData(String data)
{
if (data.equals(""))
{
try
{
int sleep = 100;
timer += sleep;
Thread.sleep(sleep);
if (timer > 3000) { // check client connection every 3000 ms
theLogger.debug("already sleep 3000");
if (System.currentTimeMillis() - this.startTime > timeout) { // server timeout
return false;
}
if (!client.isLongConnection) {
client.ps.print("HTTP/1.1 200 OK\r\n");
client.ps.print("Server: xxxx\r\n");
client.ps.print("Date: " + (new Date()) + "\r\n");
client.ps.print("Expires: Sun, 24 Apr 1981 01:29:32 GMT\r\n");
client.ps.print("Beat: Waiting"); // start server beat
client.isLongConnection = true;
} else {
client.ps.print("."); // send fault data
}
client.ps.flush();

if (client.ps.checkError()) { // client closed
theLogger.debug("remote client disconnected");
return false;
}
timer = 0;
}
} catch (Exception e)
{
theLogger.info("waiting update: " + e);
return false;
}
return true;
} else {
if (client.isLongConnection) // end server beat
{
client.ps.print("\r\n");
client.ps.flush();
}
return false;
}
}

No comments: