Solved

socket auto reconnect

Posted on 2004-03-22
40
2,243 Views
Last Modified: 2010-07-27
sample program:

Client side program:

*  Write function in client  *
      public void writeServer()
      {
            try
            {
                  System.out.println(cSocket);
                  BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
                  PrintWriter output = new PrintWriter(cSocket.getOutputStream(), true);
                  String userInput;
                  while ((userInput = stdin.readLine()) != null)
                  {
                        System.out.println(MyServer.getAlive());
                        System.out.println("in while loops");
                        //tSocket = new Socket("192.168.1.2",1234);
                        output.println("userInput");
                        System.out.println(cSocket);
                        //tSocket.close();
                  }
                  output.close();
                  stdin.close();      
            }

            catch (Exception i)
            {
                  i.printStackTrace();
            }
      }

*  Read function in client  *
      public void readServer()
      {
            try
            {
                  //System.out.println(cSocket);
                  BufferedReader input = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
                  String fromServer;
                  while ((fromServer = input.readLine()) != null && MyServer.getAlive() == true)
                  {
                        //tSocket = new Socket("192.168.1.2",1234);
                        System.out.println(MyServer.getAlive());
                        System.out.println("Server said: " + fromServer);
                        System.out.println(cSocket);
                        //tSocket.close();
                  }
                  input.close();
            }

            catch (Exception h)
            {
                  socketC();
                  retry();
            }
      }


my problem is how to establish auto reconnect if server is disconnected? and how the client detect the server is disconnected....

thanks in advance....
0
Comment
Question by:Kennywen
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 16
  • 14
  • 10
40 Comments
 
LVL 30

Expert Comment

by:Mayank S
ID: 10647779
If the server is detected, you will get an exception. It might read something like: Connection reset from peer.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10647785
It could be java.net.SocketException: Connection reset by peer.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10647792
I guess it could be SocketException or IOException.... not sure. You could try catching the exceptions and then call a method which tries to connect again?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 17

Expert Comment

by:krakatoa
ID: 10647835
You can only determine a disconnection by attempting to write to the socket.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10647874
Perhaps also by reading? Any read or write statements would throw an exception?
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10647886
If it's a PrintWriter (and it well could be if he's passing hos own protocol suite across it), then print writers dont throw exceptions as such, but set error flags which you have to interrogate. This is a bit of a semantic, since they are exceptions to all intents and purposes, but that's how it is, anyway.

If you read, then your read usually blocks anyway, so how are you going to know whether there was not meant to be any data there to collect (the client has gone to lunch), or that his connection is down? True, you could read a no-op protocol, but since you dont need to do anything with that string anyway, you may as well not bother reading it.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10647903
A clientside reconnect button might be a good idea, but you could end up having the client clicking away at it frantically thinking it will magic-up a connection, when, in fact, it is most likely a network problem that can't be redressed from the programme.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10647908
Here are a couple of lines from my own serverside code as to how I deceided to handle this :

                                                                checkurthread.printwritac.println("noOP");

                        if(checkurthread.printwritac.checkError()){

......}


0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10648047
Well, I tested this:

SERVER:

import java.net.* ;

class ServerTest
{
      public static void main ( String args[] )
            throws Exception
      {
            ServerSocket ss = new ServerSocket ( 4444 ) ;

            while ( true )
            {
                  Socket s = ss.accept () ;
                  System.out.println ( s.getInetAddress ().getHostName () + " " + s.getInetAddress ().getHostAddress () ) ;
            }
      }
}

CLIENT - 1:

import java.net.* ;
import java.io.* ;

class ClientTest
{
      public static void main ( String args[] )
            throws Exception
      {
            Socket s = new Socket ( "172.21.21.50", 4444 ) ;
            BufferedReader br = new BufferedReader ( new InputStreamReader ( s.getInputStream () ) ) ;
            System.out.println ( br.readLine () ) ;

      }

}

CLIENT-2:

import java.net.* ;
import java.io.* ;

class ClientTest
{
      public static void main ( String args[] )
            throws Exception
      {
            Socket s = new Socket ( "172.21.21.50", 4444 ) ;
            PrintWriter pw = new PrintWriter ( s.getOutputStream (), true ) ;
            Thread.sleep ( 10000 ) ;
            pw.println ( "HI" ) ;

      }

}

The first client merely attempts to read a line from the socket and the second client attempts to write a line to the socket. I started the server and then I started the clients. The Thread.sleep ( 10000 ) at the second client is given to hold the pw.println () statement, so that I have enough time to switch to the server window and close the server.

But both the clients threw a java.net.SocketException: Connection reset by peer (the first client at the br.readLine () statement and the second client at the pw.println () statement).
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10648072
>> But both the clients threw a java.net.SocketException: Connection reset by peer  ...

Yes, they will. You are terminating the java session on the socket, not simulating a network outage.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10648105
Yeah, but I guess the question was:

>> my problem is how to establish auto reconnect if server is disconnected? and how the client detect the server is disconnected....

So isn't that addressed in both the cases?
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10648119
OK, there could be several alternative topologies for the questioner's client server setup, so without those exact details, one can't say for sure. But ...

a) "How to establish auto reconnect if server is disonnected?"

What would there be to reconnect to if the server isn't there? ;)

b) "How the client detect the server is disconnected ..."

You wont be able to talk to it, that's how.





0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10648144
>> "How to establish auto reconnect if server is disonnected?"

Perhaps the questioner means that at the server-side, there seems to a disconnection (the client got disconnected), but he expressed it like: server gets disconnected from the client (but actually its the other way round). I guess that's what he meant, also because the next line would otherwise be ambiguous :-)

>> and how the client detect the server is disconnected
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10648411
The client should be more concerned first of all whether the loss of conneciton is due to a network failure at his end, rather than worrying about the server, over which he has no control anyway.

Even if the client does know that he is down, the server isnt going to know about it until it tries to write to the socket. If the server is down, then the client cant reconnect anyhow.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10648456
>> Even if the client does know that he is down, the server isnt going to know about it until it tries to write to the socket

Yeah, that's correct. But eventually it should happen at a println () or readLine () or whatever :-)
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10648652
>> Yeah, that's correct. But eventually it should happen at a println () or readLine () or whatever :-)

I think the issue has become overcomplicated, and if you dont mind me saying, the issue which you are trying to resolve is not the same one as I am talking about.

There will not be an exception thrown if one side tries to write, because printwriters *do not throw* exceptions. *You* have to trap the error flag. Using a reader is not going to tell you anything either, since it will be blocking after the last read, and wont be activated just because there is nothing to read!!

The only way I have found of coping with this situation as I said above, is to write to the socket, and check for the error flag. What you were suggesting is caught, mayank., is the termination of the session on the socket, and this is something else.

0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10648753
mayank:

run the code your code above again on two different networked machines, one client, one server obviously. Then go to your OS network connection, right-click, whatever, and disable one of them. Then see if your client or server throws the same exceptions that you mentioned it did before. ;)
0
 

Author Comment

by:Kennywen
ID: 10654795
i try to repost my question again.........

actually i have 6 java program...
1. the first java program is call MyServer.java and this program will do server.accept();, once it accept a connection then it will create 2 threads. first one is ServerWrite thread and it will handle whatever things the server want to write to a client. and second one is ServerRead thread and it will get all the things that client want to send to server.

2. MyClient.java is the client program and it will try to connect to the server(E.g. cSocket = new Socket("192.168.1.2",1234);). once connected to server then it will also create 2 threads (similar to the above thread) that is ClientWrite and ClientRead thread.

but now i facing a problem that is how the cilent program detect the server is died? And once the server is died how the client can reconnect back to the server? My suggestion is to run a infinity loop once i detect the server is died. the infinity loop will always try to connect back the server like cSocket = new Socket("192.168.1.2",1234);. is't possible?

thanks
0
 

Author Comment

by:Kennywen
ID: 10654880
>> checkurthread.printwritac.println("noOP");
>> if(checkurthread.printwritac.checkError()){

what is this 2 lines meant??
0
 

Author Comment

by:Kennywen
ID: 10655008
when i close the server program and using the function above (writeServer and readServer) it will not throw any exception. why???

thanks
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10655216
>> run the code your code above again on two different networked machines, one client, one server obviously. Then go to
>> your OS network connection, right-click, whatever, and disable one of them.

That would take some time, but I will try it.

>> My suggestion is to run a infinity loop once i detect the server is died.
>> is't possible?

It is possible, but it might be a waste.... if the server goes down, how long do you want to keep trying till it comes up again?
0
 

Author Comment

by:Kennywen
ID: 10655245
i will try until the server is up.....
0
 

Author Comment

by:Kennywen
ID: 10655251
but my problem is when i close the server program and using the function above (writeServer and readServer in client side) it will not throw any exception. why???
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10656019
>>  it will not throw any exception. why??? ...

Kennywen: I've already dealt with this. Please read my earlier comments. The concepts are simple: the sockets stay up until they are closed by Java code. If they are not closed by code, then a network failure occured, and you cannot determine why, when or how this happened properly from your programme, so the best you can do is to make code to repeatedly write to the client(s), and test the printwriter error flag.
0
 

Author Comment

by:Kennywen
ID: 10656376
>> make code to repeatedly write to the client(s),
>> test the printwriter error flag

can u give me some guide how to do the above functions?

thanks.
0
 
LVL 17

Assisted Solution

by:krakatoa
krakatoa earned 100 total points
ID: 10656471
I did already post two lines of code which are at the heart of this matter. I'll paste them in again here if you like:
 ........

                  checkurthread.printwritac.println("noOP");

                   if(checkurthread.printwritac.checkError()){
                    ......
                    }

I have a multi-way client/server chat system. Each client has a server thread serving it. Inside the server code - somewhere doesnt matter where - is a timer routine, which does a round-robin of each thread (checkurthread (sorry about the idiosyncratic names I use) in this case), every so often. The timer routine tries to write to the socket - .printwritac.println("noOP");

Then, the code immediately checks the printwriter's error flag - .printwritac.checkError().

checkError() is a method of PrintWriter.

If the write failed, then the client is probably dead. *You wont know that the client is dead* if he just pulls the network conneciton at his end, or the power goes out. *That situation woudl not trigger* an exception.

One important reason why you would want to do it this way, is that if you have several clients online together in a group, *the most important thing* is that the *server* knows who died, so it can tell that fact to the remaining clients, and maintain the group's integrity. This, after all, is a fundamental principle of the internet and of multithreading isn't it - you dont want everyone to suffer when just one customer goes belly-up.

If you leave the error trap until you are actually writing *real* data to the client group, then you have let yourself in for many logistical headaches that can be put out of the way by doing this earlier in a special loop.
0
 

Author Comment

by:Kennywen
ID: 10656499
that mean i can write a checkurthread.printwritac.println("noOP"); in the server side and set a time for example 10 seconds. if after 10 seconds the client did not receive anything from servert that mean the server is died.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10656551
Well, in theory, yes. But you are a) not going to be able to reconnect to anything (your original question), since the server wont be there, and b) you are likely to face timing problems coordinating all that. And, although I haven't tried it, doing what you suggest might create false positives, in the sense that if the timings are not perfectly synched (and they wont be), then your client might think the server is dead when it's not.
0
 

Author Comment

by:Kennywen
ID: 10656611
from ur example above: >> The timer routine tries to write to the socket - .printwritac.println("noOP");
Then, the code immediately checks the printwriter's error flag - .printwritac.checkError().

is't the client is died then the printwriter will throw an exception? else how u change the error flag?

do u have any other suggestion for me to detect the server is died beside using the timer?

thanks
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10656614
>>  for example 10 seconds. if after 10 seconds the client did not receive anything

Depending upon network traffic, congestion, etc - it might be that the server is not down and that the message gets delayed (say, it comes after 15 seconds), but you will assume that it is down.
0
 
LVL 30

Accepted Solution

by:
Mayank S earned 50 total points
ID: 10656625
>> else how u change the error flag?

You don't change it. The JVM sets it.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10656627
>>Depending upon network traffic, congestion, etc - it might be that the server is not down and that the message gets delayed (say, it comes after 15 seconds), but you will assume that it is down. >> Just said that! ;)


What you could explore I suppose is having the client "ping" the server, via a Runtime.exec(). But the conundrum here is how you tell yourself whether its *your*connection that is down, or the server's! You can only tell if you are down when you write to the socket (same situation as the server again), but ask yourself : if you had loads of clients online to the server, would you want them all sending pings or no-ops to the server? It's much easier to get the server to do that, and that's why it needs to be threaded as well, since you aren't gonna get very far testing all those connections from one server thread.

0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10656654
>> do u have any other suggestion for me to detect the server is died beside using the timer?

You are tilting at windmills here KennyWen. There is no foolproof way to detect network outages of nodes. You can only know that something is wrong if you try to write to it, and even then you dont know, do you, whether it's you or the server that is down. You have to *assume* that if the conenction is unwritable when *in Java code* you did not *explicitly* close the socket, then you suffered a network loss, or the server did.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10656663
>> Just said that! ;)

I know. Sorry I had the page open for long and didn't refresh. By the time I replied to the "set a time for example 10 seconds" comment, I saw there were two more comments.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 10656671
LOL!
0
 

Author Comment

by:Kennywen
ID: 10664821
now i'm facing another problem that is the printwritac.checkError(). will return false when the fiirst time writtng to server if the server is close and return true when the second time writtng to server.

mayankeagle, do u face the above problem before?

console screen as below:
Socket[addr=/192.168.1.2,port=1234,localport=3141]
first time write to server
false
second time write to server
true

thanks.....
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10664830
It returns a true if it encounters an error and false if it does not. In the first case, I guess it did not encounter an error....

>> if the server is close

Perhaps that was not the case when you wrote for the first time.
0
 

Author Comment

by:Kennywen
ID: 10664895
i'm sure the server is close(i press ctrl-C to end the server program) b4 i write something to server... but dun know why the first time the printwritac.checkError(). will return false. any idea?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10666750
How do you ascertain that the server is closed before writing anything? Have you given sufficient delay at the client-side or something?
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

687 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question