views:

401

answers:

1

Well as the title says how can i detect a disconnect with "ReceiveAsync" with all other .net network patterns you could just look if you recived 0 bytes or if any exception was throw however this does not seem to be true any more with this pattern...

My first recive return 0 bytes but the second works thats why im confused....

+1  A: 

It's just the same:

        void OnReceiveComplete(IAsyncResult iar)
        {
            try
            {
                int count = sock.EndReceive(iar);
                if (count == 0)
                {
                    Console.WriteLine("{0} closed by remote host", ID);
                    sock.Close();
                }
                else
                {
                    int total = Interlocked.Increment(ref totalBytes);
                    Console.WriteLine("{0} received {1} (total: {2})",
                        ID, buff[0], total);
                    StartReceive();
                }
            }
            catch (Exception x)
            {
                Console.WriteLine("{0} error from EndReceive: {1}", ID, x);
            }
        }
Len Holgate
Doesn't the socket automatically close when a disconnection occurs?
strager
Im using ReceiveAsync not BeginReceive ill post some code later this week when i have cut out the ugly parts
Petoj
Petoj - ah, sorry.
Len Holgate
strager - I hope not! All that has happened here is that the client has closed its send side (by calling Shutdown(Send)) and it wont send any more data. The connection is now 'half open' and you can still send data if you need to. If the socket automatically closed then this would not be possible.
Len Holgate