Ayse
Ayse

Reputation: 2754

How to handle when a Client or Server is Down in a UDP Application

I am developing a windows application for Client Server communication using UDP, but since UDP is connectionless, whenever a Client goes down, the Server does not know that Client is off and keeps sending the data. Similar is the case when a Server is down. How can I cater this condition that whenever any of the Client or Server is down, the other party must know it and can handle it. Waiting for reply.

Upvotes: 1

Views: 1442

Answers (1)

Anish Ramaswamy
Anish Ramaswamy

Reputation: 2351

What you are asking is beyond the scope of UDP. You'd need to implement your own protocol, over UDP, to achieve this.

One simple idea could be to periodically send keepalive messages (TCP on the other hand has this feature).

You can have a simple implementation as follows:

  • Have a background thread keep sending those messages and waiting for replies.
  • Upon receiving replies, you can populate some sort of data structure or a file with a list of alive devices.
  • Your other main thread (or threads) can have the following changes:

    1. Before sending any data, check if the client you're going to send to is present in that file/data structure.
    2. If not, skip this client.
    3. Repeat the above for all remaining clients in the populated file/data structure.

One problem I can see in the above implementation is analogous to the RAW hazard from the main thread's perspective.

Use the following analogy instead of the mentioned example for the RAW hazard,

  • i1 = Your background thread which sends the keepalive messages.
  • i2 = Your main thread (or threads) which send/receive data and do your other tasks.
  • The RAW hazard here would be when i2 tries to read the data structure/file which is populated by i1 before i1 has updated it.
  • This means (worst case), i2 will not get the updated list and it can miss out a few clients this way.
  • If this loss would be critical, I can suggest that you possibly have a sort of mechanism whereby i1 will signal i2 when it completes any-ongoing writing.
  • If this loss is not critical, then you can skip the above mechanism to make your program faster.

Explanation for Keepalive Messages:

You just need to send a very lightweight message (usually has no data. Just the header information). Make sure this message is unique. You do not want another message being interpreted as a keepalive message.

You can send this message using a sendto() call to a broadcast address. After you finish sending, wait for replies for a certain timeout using recv().

Log every reply in a data structure/file. After the timeout expires, have the thread go to sleep for some time. When that time expires, repeat the above process.

To help you get started writing good, robust networking code, please go through Beej's Guide to Network Programming. It is absolutely wonderful. It explains many concepts.

Upvotes: 4

Related Questions