Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Check if socket is disconnected?

How can you check if a non-blocking socket is disconnect without using Poll?

like image 506
Will Avatar asked Apr 18 '11 04:04

Will


1 Answers

Create a cusomt socket class inheriting .net socket class :

public delegate void SocketEventHandler(Socket socket);
    public class CustomSocket : Socket
    {
        private readonly Timer timer;
        private const int INTERVAL = 1000;

        public CustomSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
            : base(addressFamily, socketType, protocolType)
        {
            timer = new Timer { Interval = INTERVAL };
            timer.Tick += TimerTick;
        }

        public CustomSocket(SocketInformation socketInformation)
            : base(socketInformation)
        {
            timer = new Timer { Interval = INTERVAL };
            timer.Tick += TimerTick;
        }

        private readonly List<SocketEventHandler> onCloseHandlers = new List<SocketEventHandler>();
        public event SocketEventHandler SocketClosed
        {
            add { onCloseHandlers.Add(value); }
            remove { onCloseHandlers.Remove(value); }
        }

        public bool EventsEnabled
        {
            set
            {
                if(value)
                    timer.Start();
                else
                    timer.Stop();
            }
        }

        private void TimerTick(object sender, EventArgs e)
        {
            if (!Connected)
            {
                foreach (var socketEventHandler in onCloseHandlers)
                    socketEventHandler.Invoke(this);
                EventsEnabled = false;
            }
        }

        // Hiding base connected property
        public new bool Connected
        {
           get
           {
              bool part1 = Poll(1000, SelectMode.SelectRead);
              bool part2 = (Available == 0);
              if (part1 & part2)
                 return false;
              else
                 return true;
           }
        }
    }

Then use it like this :

        var socket = new CustomSocket(
                //parameters
                );

        socket.SocketClosed += socket_SocketClosed;
        socket.EventsEnabled = true;


        void socket_SocketClosed(Socket socket)
        {
            // do what you want
        }

I have just implemented a Socket close event in each socket. so your application should register event handlers for this event. then socket will inform your application if it was closed itself ;)

if there was any problem with code, inform me.

like image 61
Farzin Zaker Avatar answered Sep 30 '22 18:09

Farzin Zaker