Connection close in Java Servlet and SSE - java

I try to implement Server-Sent-Event in my Webapp with Java Serlvet on server.
Is it possible to check in Servlet that connection is closed by client? The loop while(true) in Servlet is infinite even if client browser is closed.
Client code
function startLogSSE(lastEventId, level) {
var eventSource = new EventSource("log-sse?last-event-id=" + lastEventId + "&level=" + level);
eventSource.onmessage = function (event) {
document.getElementById('log').innerHTML = event.data + "\n" + document.getElementById('log').innerHTML;
};
}
Server code
public class LogSSEServlet extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(LogSSEServlet.class);
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
// get logger purgerDB appender
PurgerDBAppender appender = LogUtils.getPurgerDBAppender();
if (appender == null) {
writer.write("data: [ERROR] Appender 'purgerDB' isn't found for logger 'com.bp3'\n\n");
writer.close();
return;
}
int eventId = 0;
// get last-event-id
String lastEventId = request.getHeader("last-event-id");
if (lastEventId == null) {
// try to get lastEventId from parameter
lastEventId = request.getParameter("last-event-id");
}
if (lastEventId != null) {
try {
eventId = Integer.parseInt(lastEventId);
} catch (NumberFormatException e) {
logger.error("Failed to parse last-event-id: " + lastEventId);
}
}
String minLevel = request.getParameter("level");
if (minLevel == null) {
minLevel = "TRACE";
}
// get logs from purgerDB logger appender
LogServices logServices = new LogServices();
try {
logServices.open();
} catch (SQLException e) {
throw new ServletException(e);
}
try {
while (true) {
List<LogMessage> messages = logServices.getLastMessages(Level.toLevel(minLevel), eventId, 0);
if (messages.size() > 0) {
writer.write("id: " + messages.get(0).getEventId() + "\n");
writer.write("data: " + LogUtils.formatLog(messages) + "\n");
writer.flush();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
}
} catch (SQLException e) {
throw new ServletException(e);
} finally {
logServices.closeQuietly();
}
}
}

Is it possible to check in Servlet that connection is closed by client?
Eventually an exception will be thrown: either an IOException: connection reset if you are streaming directly to the socket, or an OutOfMemoryError if the container is streaming to memory, which it does when you aren't using a fixed-length or chunked transfer mode.
The loop while(true) in Servlet is infinite even if client browser is closed.
No it isn't.

One way to check, wihin the Servlet, that connection is closed, is using the writer.checkError() method. I tested this fix on Chrome and it works. Your code would be:
boolean error=false;
while (!error) {
//...
writer.write("data: " + /*...*/ "\n");
//writer.flush();
error = writer.checkError(); //internally calls writer.flush()
}
Details:
The PrintWriter's API says:
Methods in this class never throw I/O exceptions, although some of its
constructors may. The client may inquire as to whether any errors have
occurred by invoking checkError().
and the checkError() says:
Flushes the stream if it's not closed and checks its error state

Related

how to restart file uploading when an exception occurs

I am working on a java application in which I am facing a problem. When I send a file to a server and an exception is thrown, the file is not sent. How can I retry sending the file?
public void uploadtxtFile(String localFileFullName, String fileName, String hostDir)
throws Exception {
File file = new File(localFileFullName);
if (!(file.isDirectory())) {
if (file.exists()) {
FileInputStream input = null;
try {
input = new FileInputStream(new File(localFileFullName));
if (input != null) {
hostDir = hostDir.replaceAll("//", "/");
logger.info("uploading host dir : " + hostDir);
//new
// TestThread testThread=new TestThread(hostDir,input);
// Thread t=new Thread(testThread);
//
// try{
// t.start();
//
// }catch(Exception ex){
// logger.error("UPLOADE start thread create exception new:" + ex);
// }
// // new end
DBConnection.getFTPConnection().enterLocalPassiveMode();
// the below line exeption is come
boolean bool = DBConnection.getFTPConnection().storeFile(hostDir, input);
//input.close();//new comment
if (bool) {
logger.info("Success uploading file on host dir :"+hostDir);
} else {
logger.error("file not uploaded.");
}
} else {
logger.error("uploading file input null.");
}
}catch(CopyStreamException cs)
{ logger.error("Copy StreamExeption is come "+cs);
} catch(Exception ex)
{
logger.error("Error in connection ="+ex);//this is catch where I handle the exeption
}finally {
// boolean disconnect= DBConnection.disConnect();
input.close();
}
} else {
logger.info("uploading file is not exists.");
}
}
}
This is the code and I want to restart the file uploading but I don't have any idea. I tried it using the thread but the exception is thrown again. I also tried to use a while loop, but it loops infinitely and also shows the exception as well as another exception.
Below is the thread code that I use:
public void run() {
System.out.println("Enter Thread TestThread");
DBConnection.getFTPConnection().enterLocalPassiveMode();
// System.out.println("Error in DBConnection ");
//here server timeout error is get
boolean bool1=false;
boolean bool=true;
try {
bool = DBConnection.getFTPConnection().storeFile(hostDir1, input1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//disconnect();
try {
input1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bool) {
System.out.println("File is Uploded");
} else {
while(bool!=true){
try {
DBConnection.getFTPConnection().enterLocalPassiveMode();
bool1=DBConnection.getFTPConnection().storeFile(hostDir1, input1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//disconnect();
try {
input1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("file not uploaded."+bool1);
bool=bool1;
}
}
}
}
}
Can any one have a solution to how to upload the file to the server?
The exception is shown below:
Software caused connection abort: recv failed
Software caused connection abort: socket write error
org.apache.commons.net.io.CopyStreamException: IOException caught while copying.
Add a static class as below in a class from where you are calling the method which need to be retried:
static class RetryOnExceptionStrategy {
public static final int DEFAULT_RETRIES = 3;
public static final long DEFAULT_WAIT_TIME_IN_MILLI = 2000;
private int numberOfRetries;
private int numberOfTriesLeft;
private long timeToWait;
public RetryOnExceptionStrategy() {
this(DEFAULT_RETRIES, DEFAULT_WAIT_TIME_IN_MILLI);
}
public RetryOnExceptionStrategy(int numberOfRetries,
long timeToWait) {
this.numberOfRetries = numberOfRetries;
numberOfTriesLeft = numberOfRetries;
this.timeToWait = timeToWait;
}
/**
* #return true if there are tries left
*/
public boolean shouldRetry() {
return numberOfTriesLeft > 0;
}
public void errorOccured() throws Exception {
numberOfTriesLeft--;
if (!shouldRetry()) {
throw new Exception("Retry Failed: Total " + numberOfRetries
+ " attempts made at interval " + getTimeToWait()
+ "ms");
}
waitUntilNextTry();
}
public long getTimeToWait() {
return timeToWait;
}
private void waitUntilNextTry() {
try {
Thread.sleep(getTimeToWait());
} catch (InterruptedException ignored) {
}
}
}
Now wrap your method call as below in a while loop :
RetryOnExceptionStrategy errorStrategy=new RetryOnExceptionStrategy();
while(errorStrategy.shouldRetry()){
try{
//Method Call
}
catch(Exception excep){
errorStrategy.errorOccured();
}
}
Basically you are just wrapping you method call in while loop which will
keep returnig true till your retry count is reached to zero say you started with 3.
Every time an exception occurred, the exception is caught and a method is called
which will decrement your retryCount and method call is again executed with some delay.
A general way of working with such application is:
Create a class, say, UploadWorker which extends Callable as the wrapper. Make the wrapper return any error and detail information you need when it fails.
Create a ExecutorService (basically a thread pool) for this wrapper to run in threads.
Submit your UploadWorker instance and then you get a Future. Call get() on the future to wait in blocking way or simply wait some time for the result.
In case the get() returns you the error message, submit your worker again to the thread pool.

java.net.SocketException: Broken pipe smpp.logica library

why i got this error
20:43:40,798 ERROR Tx:809 - java.net.SocketException: Broken pipe
java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:109)
at com.logica.smpp.TCPIPConnection.send(TCPIPConnection.java:353)
at com.logica.smpp.Transmitter.send(Transmitter.java:79)
at com.logica.smpp.Session.send(Session.java:993)
at com.logica.smpp.Session.send(Session.java:1048)
at com.logica.smpp.Session.enquireLink(Session.java:789)
at com.logica.smpp.Tx.kirimEnquireLink(Tx.java:795)
at com.logica.smpp.Tx.access$0(Tx.java:777)
at com.logica.smpp.Tx$1.run(Tx.java:120)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
..I'm Using Open smpp logica library to create smsc client..for a few hours it's work but then the error come out..when i'm trying to send enquiry link,,the session I create is syncronize and the type of connection is Transceiver here's a piece of code i used to bind and to enqury link
private void bind()
{
debug.enter(this, "SMPPTest.bind()");
try {
if (bound) {
System.out.println("Already bound, unbind first.");
return;
}
BindRequest request = null;
BindResponse response = null;
String syncMode = (asynchronous ? "a" : "s");
// type of the session
syncMode = getParam("Asynchronous/Synchronnous Session? (a/s)",
syncMode);
if (syncMode.compareToIgnoreCase("a")==0) {
asynchronous = true;
} else if (syncMode.compareToIgnoreCase("s")==0) {
asynchronous = false;
} else {
System.out.println("Invalid mode async/sync, expected a or s, got "
+ syncMode +". Operation canceled.");
return;
}
// input values
bindOption = getParam("Transmitter/Receiver/Transciever (t/r/tr)",
bindOption);
if (bindOption.compareToIgnoreCase("t")==0) {
request = new BindTransmitter();
} else if (bindOption.compareToIgnoreCase("r")==0) {
request = new BindReceiver();
} else if (bindOption.compareToIgnoreCase("tr")==0) {
request = new BindTransciever();
} else {
System.out.println("Invalid bind mode, expected t, r or tr, got " +
bindOption + ". Operation canceled.");
return;
}
ipAddress = getParam("IP address of SMSC", ipAddress);
port = getParam("Port number", port);
TCPIPConnection connection = new TCPIPConnection(ipAddress, port);
connection.setReceiveTimeout(20*1000);
session = new Session(connection);
systemId = getParam("Your system ID", systemId);
password = getParam("Your password", password);
// set values
request.setSystemId(systemId);
request.setPassword(password);
request.setSystemType(systemType);
request.setInterfaceVersion((byte)0x34);
request.setAddressRange(addressRange);
// send the request
System.out.println("Bind request " + request.debugString());
if (asynchronous) {
pduListener = new SMPPTestPDUEventListener(session);
response = session.bind(request,pduListener);
} else {
response = session.bind(request);
}
System.out.println("Bind response " + response.debugString());
if (response.getCommandStatus() == Data.ESME_ROK) {
System.out.println("CommandID "+response.getCommandId());
bound = true;
}
} catch (Exception e) {
event.write(e,"");
debug.write("Bind operation failed. " + e);
System.out.println("Bind operation failed. " + e);
} finally {
debug.exit(this);
}
}
the code for enquiry link is
private void kirimEnquireLink()
{
try
{
log.info("Send enquireLink!");
EnquireLink request = new EnquireLink();
EnquireLinkResp response = new EnquireLinkResp();
// synchronized (session) {
// session.enquireLink(request);
// }
if(asynchronous)
{
session.enquireLink(request);
}else
{
response = session.enquireLink(request);
System.out.println("Enquire Link Response "+request.debugString());
}
}
catch (Exception e)
{
bound = false;
// unbind();
log.error(e, e);
}
}
i called enquiry link every 10 second,, any idea why
The problem you are facing is that there is never insurance that connection will be always available, nor the session. Many different external reasons can bring the link between ESME and SMSC down. My suggestion, try-catch the enquire_link operations and the submit operations, evaluate the Exception and take action.
I've successfully implemented recursive method calls to deal with this issue as follows
/**
* Connect to ESME and submit a message, if binding process fails, reattempt
* to reconnect and submit.
*/
public void connect() {
try {
//Create connection
BindRequest request = null;
request = new BindTransciever();
connection = new TCPIPConnection("localhost", 17632);
connection.setReceiveTimeout(20 * 1000);
session = new Session(connection);
//Prepare request
request.setSystemId("pavel");
request.setPassword("wpsd");
request.setSystemType("CMT");
request.setInterfaceVersion((byte) 0x34);
request.setAddressRange(new AddressRange());
pduListener = new SMPPTestPDUEventListener(session);
//Session binding process, if it fails, we are thrown to the catch section
//with a BrokenPipe (IOException)
session.bind(request, pduListener);
//Prepare message
SubmitSM msg = new SubmitSM();
// set values
msg.setDestAddr("04234143939");
msg.setShortMessage("hello");
msg.assignSequenceNumber(true);
//Send to our custom made submitMessage method that reattempts if failure
submitMessage(msg);
} catch (Exception ex){
//Analyze what type of exception was
if (ex instanceof IOException || ex instanceof SocketException){
//IOException relate to the brokenpipe issue you are facing
//you need to close existing sessions and connections
//restablish session
if (this.connection!=null){
this.connection.close();
}
//This is a recursive call, I encourage you to elaborate
//a little bit this method implementing a counter so you
//don't end up in an infinite loop
this.connect();
} else {
//LOG whatever other exception thrown
}
}
}
/**
* Submit message to SMSC, if it fails because of a connection issue, reattempt
* #param message
*/
private void submitMessage(SubmitSM message){
try{
session.submit(message);
} catch (Exception ex){
//Analyze what type of exception was
if (ex instanceof IOException || ex instanceof SocketException){
//IOException relate to the brokenpipe issue you are facing
//you need to close existing sessions and connections
//restablish session and try to submit again
if (this.connection!=null){
this.connection.close();
}
//Call a rebind method
this.bind();
//This is a recursive call, I encourage you to elaborate
//a little bit this method implementing a counter so you
//don't end up in an infinite loop
this.submitMessage(message);
} else {
//LOG whatever other exception thrown
}
}
}
Do the same with the enquire_link, try-catch, during IOException rebind, and reattempt. Do not forget to add a couter and a maximum ammount of attempts in order to avoid infinite loops during recursive calls.
You do not need to enquire_link every 10 seconds. Most providers will let you know how often it needs to be done, the standard is 10 minutes.

Java Servlets with Thread is blocking?

I'm trying to use my own form of connection pooling to handle database connections but it seems to be blocking for some reason even though I used a thread, can someone help me point out my mistake please.
This is the servlet code with the thread class.
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// PrintWriter out = response.getWriter();
OutputStream ostream = response.getOutputStream();
PrintStream out = new PrintStream(ostream, true, "UTF8");
try {
response.setContentType("text/html");
String test = request.getParameter("test");
System.out.println("Received text: " + test);
if(test.equals("free"))
{
for (int i = 0; i < list.size(); i++) {
dbcm.freeConnection(list.get(i));
}
list.clear();
}else
{
GetConnThread gct = new GetConnThread(test, dbcm);
gct.start();
}
} catch (Exception e) {
e.printStackTrace();
out.println("fail");
} finally {
out.close();
}
}
private class GetConnThread extends Thread
{
private String test;
private DBConnectionManager dbcm;
public GetConnThread(String test, DBConnectionManager dbcm)
{
this.test = test;
this.dbcm = dbcm;
}
public void run()
{
try {
Connection conn = dbcm.getConnection(test);
list.add(conn);
System.out.println(conn);
System.out.println("list size: " + list.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is the getConnection method in the DBConnectionManager
public synchronized Connection getConnection(String test) throws CGFatalException {
Connection con = null;
boolean connectionIsValid = false;
if (freeConnections.size() > 0) {
con = (Connection) freeConnections.firstElement();
freeConnections.removeElementAt(0);
connectionIsValid = validateConnection(con);
if (connectionIsValid == false) {
con = getConnection(test);
}
} else if (maxConn == 0 || checkedOut < maxConn) {
con = newConnection();
connectionIsValid = validateConnection(con);
if (connectionIsValid == false) {
con = getConnection(test);
}
}else
{
System.out.println("No available connections for " + test + ", try again in 2 secs....");
try {
Thread.sleep(2000);
con = getConnection(test);
} catch (Exception e) {
e.printStackTrace();
}
}
if (con != null && connectionIsValid == true) {
checkedOut++;
}
System.out.println("checkedOut: " + checkedOut);
System.out.println("maxConn: " + maxConn);
return con;
}
I set the max connections to 2 so after I call the servlet the 3rd time it goes to this line of code:
System.out.println("No available connections for " + test + ", try again in 2 secs....");
When I call it the 4th time, I'm expecting
System.out.println("No available connections for " + test + ", try again in 2 secs....");
to start as a seperate thread, but the 3rd call seems to be blocking it, the endless loop is expected because I was hoping to call "free" to clear the connections and everything goes back to normal.
Your getConnection method is synchronized. Every other thread is going to block on that lock acquisition until the "third" request successfully gets a connection and proceeds.

Full-duplex server socket implementaion, seperate read and write thread?

I want to read and write(randomly from server to client) on same server socket (java application). My client to server write and read work fine in a loop. At server with response write properly.
But if i am trying to write at server randomly some command. i do not have solution, first of all my question is :
is it possible at server side to write command to client ramdonly on same socket?
if possible, any suggestion or pointer how to do it?
please give me some pointer where I can read the material about this scenario ?
thanks in advance.
public class ContentServerSocket extends ServerSocket {
private final static int PORT = 4444;
protected static boolean XYZGONE = false;
public static Content content;
public ContentServerSocket(xyzService service) throws IOException {
super(PORT);
while (true) {
Log.d(TAG, "Waiting for new request from client(content) ....");
new HandleRequest(accept(), service).start();
}
}
public static void xyzRunAway() {
Log.d(TAG," Content Serv er 1 ");
XYZGONE = true;
}
}
class HandleRequest extends Thread {
private final static String TAG = "ContentServerSocket:Thread for a request:";
private Socket client;
private xyzService service;
private static Context context;
HandleRequest(Socket client, SuggestionService service) {
this.client = client;
this.service = service;
context = xyzService.serviceContext();
}
public void run() {
while (true) {
try {
Log.d(TAG, " Step 1: client: Received request MSG for Check... ");
PrintWriter out = new PrintWriter(client.getOutputStream(),
true);
BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream(), "utf-8"));
String request = "";
String tmpLine = null;
Log.d(TAG, " Step Xyz waiting data from the client ... ");
while ((tmpLine = in.readLine()) != null) {
if (tmpLine.length() > 0) {
request += tmpLine;
//if (tmpLine.toLowerCase().contains("</contentInfo>")) {
if (tmpLine.contains("</contentInfo>")) {
Log.d(TAG, " Server : broke because of </contentInfo>");
break;
}
} else {
Log.d(TAG, " Step NULL : ");
request = "";
}
}
Log.d("Robin", " Step 2: Actual request received from the client : : " + request);
if (request.length() == 0) {
Log.d("Robin",
" client got 0 length request, thread stop!");
throw new Exception();
}
//XMLParser xmlParser = new XMLParser(new ByteArrayInputStream(
// request.getBytes("UTF-8")));
Log.d(TAG, " Step 3 : ");
RequestParser readxmlrequest = new RequestParser(request);
String requestType = readxmlrequest.parsingXmlRequestFromContent();
Log.d(TAG, " Step 4 requestType : " + requestType);
//TODO : need to get the result and pas to the out.println..
//String result = processXML(xmlParser);
String result = responseToContentRequest(readxmlrequest,requestType);//null; //TODO need to complete.
Log.d(TAG, " Step 5 result : "+result);
(((((((((())))))))))";
if (result != null && result.length() > 0) {
//oos.writeObject(result);
Log.d("Robin", " Writing response to socket ... ");
out.println(result + "\n");
out.flush();
Log.d("Robin", " Writing flush completed ");
}
if(ContentServerSocket.XYZGONE) {
Log.d(TAG," XYZGONE >>>>>>>> ");
ContentServerSocket.XYZGONE = false;
String tmp = "<ssr> OK Done .......</ssr>";
out.println(tmp + "\n");
Log.d("Content Server Socket ", "xyz:" + tmp);
out.flush();
}
} catch (IOException ioException) {
Log.d("Robin", " IOException on socket listen: " + ioException);
}
catch (Exception e) {
Log.d("Robin", " outer exception: " + e.toString());
break;
}
finally {
if (client == null || client.isClosed()
|| !client.isConnected()) {
Log.d(" Robin ", " client is null");
break;
}
}
//break;
}
Log.d("Robin", " thread stop... ");
}
So , I fixed it . I just need to maintain two different thread.
1) read.
2)write.
In the above code i just started one more thread for write .
insert the code in Run function of above code.
====================================================
Runnable r1 = new Runnable() {
public void run() {
try {
while (true) {
System.out.println("Hello, world!");
if(ContentServerSocket.XYZGONE) {
Log.d(TAG," XYZGONEY >>>>>>>> ");
ContentServerSocket.XYZGONE = false;
String tmp = "<ssr> OK Done .......</ssr>";
out.println(tmp + "\n");
Log.d("Content Server Socket ", "XYZGONE :" + tmp);
out.flush();
}
Thread.sleep(1000L);
}
} catch (InterruptedException iex) {}
}
};
Thread thr1 = new Thread(r1);
==================================
Then Start the thread in the wile loop of read.
with the following code with a check.
====================================
if(!thr1.isAlive())thr1.start();
Thanks everyone, who respond my question..
Yes it is possible to write data from multiple threads on a server or on a client to an existing socket. However you have to make sure the requests do not overlap, and the receiving side actually knows what is written from who.
If you use a line based protocol you can define each message is a single line. In that case you should synchronize multiple threads in a way that only one is writing parts of that line at any given moment.
Your code is a bit too big to understand where your problem is, sorry.
Maybe this tutorial helps? There are quite many out there:
http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html

Blackberry Best way to retry connection if failed?

I have the following code, i want to be able to restart the thread if an exception occurred while processing a request.
The following in the run method of a thread:
int status = httpConn.getResponseCode();
if (status == HttpConnection.HTTP_OK) {
// Is this html?
String contentType = httpConn
.getHeaderField(HEADER_CONTENTTYPE);
boolean htmlContent = (contentType != null && contentType
.startsWith(CONTENTTYPE_TEXTHTML));
InputStream input = s.openInputStream();
byte[] data = new byte[1000];
int len = 0;
int size = 0;
StringBuffer raw = new StringBuffer();
while (-1 != (len = input.read(data))) {
// Exit condition for the thread. An
// IOException
// is
// thrown because of the call to
// httpConn.close(),
// causing the thread to terminate.
if (_stop) {
httpConn.close();
s.close();
input.close();
}
raw.append(new String(data, 0, len));
size += len;
}
// raw.insert(0, "bytes received]\n");
// raw.insert(0, size);
// raw.insert(0, '[');
content = raw.toString();
if (htmlContent) {
content = prepareData(raw.toString());
}
input.close();
} else {
try{
httpConn.close();
}catch (Exception e) {
// TODO: handle exception
}
errorDialog(status+", status code");
retryFeed(getUrl(), "Network error. Retrying...");
}
s.close();
} else {
errorDialog("Sorry Insufficient Network Coverage.");
return;
}
} catch (IOCancelledException e) {
errorDialog(e.getMessage());
retryFeed(getUrl(), "Network error. Retrying...");
} catch (IOException e) {
errorDialog(e.getMessage());
retryFeed(getUrl(), "Network error. Retrying...");
}
What is the safest way to retry the connection if failed?
Thanks.
//New This is the Error thread. That check for errors in the connection... will this help? and is it the most efficient method? thanks..
/Error Thread - Thread to check errors/
private class ErrorThread extends Thread {
private static final int TIMEOUT = 3000; // EVERY 3 Seconds
private boolean hasException = false;
private String _theUrl;
/**
* Stops this thread from listening for messages
*/
private synchronized void stop()
{
hasException =false;
}
/**
* Listens for incoming messages until stop() is called
* #see #stop()
* #see java.lang.Runnable#run()
*/
public void run()
{
try
{
while (true) {
if((hasException==true))
{
// Synchronize here so that we don't end up creating a connection that is never closed.
errorDialog("Will Fetch new");
synchronized(this)
{
hasException=false;
if (!_connectionThread.isStarted()) {
fetchPage(_theUrl);
} else {
createNewFetch(_theUrl);
}
}
}
try {
//errorDialog("No exception.");
sleep(TIMEOUT);
} catch (InterruptedException e)
{
errorDialog("Exceptions"+e.toString()+e.getMessage());
System.exit(1);
//System.exit(0);/*Kill System*/
}
}
}
catch (Exception except)
{
}
}
public void setActive(boolean exception,String url)
{
this.hasException=exception;
this._theUrl=url;
}
}
If the connecrtion fails, typically, you want to close it, pause a small time, and retry. The purpose of the pause is to prevent your device from devoting excessive resources to trying to connect to a server that's having issues.

Categories

Resources