简体   繁体   中英

closing sockets in asynchronous sockets

I have developed server listening to multiple clients using asynchronous sockets. I have used the following method for stopping server from listening to clients.

   //Button 2 -- To Stop Server
    private void button2_Click(object sender, EventArgs e)
    {
        socket.Shutdown(SocketShutdown.Both);
        socket.Disconnect(false);
        socket.Close();
        socket.Dispose();
     }

But problem is that when I restart the server it shows error socket connection in use. So what is the proper way for closing sockets ans stopping server. I need to stop the server as soon as I press button in UI.

Finally I was able to solve my problem. Using the following code I was able to shutdown server cleanly : -

 private void button2_Click(object sender, EventArgs e)
    {
        if (active_clients.Count >= 0)
        {
            // active client is the list of sockets clients were connected before              
             //server shutdown.
            active_clients.ForEach(delegate(Socket s)
            {
                try
                {
                    s.Shutdown(SocketShutdown.Both);
                }
                catch (ObjectDisposedException ex)
                {
                    if (ex.InnerException is SocketException)
                    {
                        MessageBox.Show("some message");
                        return;
                    }
                }
                s.Close();

            });
            active_clients.Clear();
        }
        try
        {
            serverSocket.Close();
        }
        catch (Exception)
        {
            return;
        }
    }

If you want to shut down your server application you should also close all open client connections. These are not closed when you close the listening socket (that I assume is the variable socket ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM