views:

323

answers:

1

Hello!

I have a program in c# in which i create a socket, binding it, begin listening and then using beginaccept! but then when I try to close\shutdown the socket I get exceptions from the beginaccept AsyncCallback method!

     private void start_listening()
        {

            main_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iplocal = new IPEndPoint(IPAddress.Any, 11150);
            main_socket.Bind(iplocal);
            main_socket.Listen(5);
            main_socket.BeginAccept(new AsyncCallback(OnClientConnect), null);
          }


        private void Disconnect_Click(object sender, EventArgs e)
        {
            main_socket.Shutdown(SocketShutdown.Both);
            main_socket.Close();
        }

        public void OnClientConnect(IAsyncResult asyn)
        {

            try
            {
                clients[connected_clients] = new Client("CHANGEME", "127.0.0.1", this);
                clients[connected_clients].Socket = main_socket.EndAccept(asyn);
                clients[connected_clients].WaitForData();
                main_socket.BeginAccept(OnClientConnect, null);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
}

many thanks!

+5  A: 

When main_socket is closed, OnClientConnect() will be called but main_socket.EndAccept() is supposed to throw an ObjectDisposedException. Perhaps you want to catch that exception and treat it as a "The listener socket has been closed" message.

The other problem with your code is that main_socket is not actually connected to anything. Calling main_socket.Shutdown() in Disconnect_Click() might throw too, but this time it should be a SocketException saying that the socket is not connected. I would remove that main_socket.Shutdown() call.

Gonzalo
+1. Unfortunately there is no properties such as "IsClosed". Socket is from the dark unmanaged world of Cthulhu.
Roubachof
Actually, there is a way: Socket.Handle will be -1 if the socket was closed in the local side of the connection.
Gonzalo
thank guys for the answers! i'll check that.so u say that when i get throwed in onclientconnect becuase of the socket is closed i should handle that excaption?
Hipno
Correct. Catching ObjectDisposedException will take care of it.
Gonzalo