Alex
Alex

Reputation: 11137

client-server question

If i have a client that is connected to a server and if the server crashes, how can i determine, form my client, if the connection is off ? the idea is that if in my client's while i await to read a line from my server ( String a = sr.ReadLine(); ) and while the client is waiting to recieve that line , the server crashes , how do i close that thread that contains my while ?

Many have told me that in that while(alive) { .. } I should just change the alive value to true , but if my program is currently awaiting for a line to read, it won't get to exit the while because it will be trapped at sr.ReadLine() .

I was thinking that if i can't send a line to the server i should just close the client thread with .abort() . Any Ideas ?

Upvotes: 0

Views: 120

Answers (5)

3Dave
3Dave

Reputation: 29041

Is the server app your own, or something off the shelf?

If it's yours, send a "heart beat" every couple of seconds to let the clients know that the connection and service are still alive. (This is a bit more reliable than just seeing if the connection is closed since it may be possible for the connection to remain open while the server app is locked.)

Upvotes: 1

Unmesh Kondolikar
Unmesh Kondolikar

Reputation: 9312

Have a TimeOut parameter in ReadLine method which takes a TimeSpan value and times out after that interval if the response is not received..

public string ReadLine(TimeSpan timeout)
{
   // ..your logic.
)

For an example check these SO posts -

Implementing a timeout on a function returning a value

Implement C# Generic Timeout

Upvotes: 2

P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

If the server crashes I imagine you will have more problems than just fixing a while loop. Your program may enter an unstable state for other reasons. State should not be overlooked. That being said, a nice "server timed out" message may suffice. You could take it a step further and ping, then give a slightly more advanced message "server appears to be down".

Upvotes: 0

Brent Arias
Brent Arias

Reputation: 30165

Try to avoid any strategy that relies on thread abort(). If you cannot avoid it, make sure you understand the idiom for that mechanism, which involves having a separate appdomain and catching ThreadAbortException

Upvotes: 0

jgauffin
jgauffin

Reputation: 101140

That the server crashes has nothing to do with your clients. There are several external factors that can make the connection go down: The client is one of them, internet/lan problems is another one.

It doesn't matter why something fails, the server should handle it anyway. Servers going down will make your users scream ;)

Regarding multi threading, I suggest that you look at the BeginXXX/EndXXX asynchronous methods. They give you much more power and a more robust solution.

Upvotes: 0

Related Questions