1

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.

prattom
  • 1,625
  • 11
  • 42
  • 67
  • This sounds like a [TIME_WAIT](http://stackoverflow.com/questions/4306372/preventing-time-wait-using-net-async-api) issue. – Cory Nelson Sep 03 '13 at 15:48

2 Answers2

2

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;
        }
    }
prattom
  • 1,625
  • 11
  • 42
  • 67
  • You can jolly things along by triggering garbage collection `GC.Collect();` on your way out of the app. As Roland mentions below you also ought to be signalling all of your sessions to die. – Peter Wone Sep 04 '13 at 05:47
  • 1
    But I have always read never use GC.Collect() unless necessary. – prattom Sep 04 '13 at 06:42
0

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).

Roland Bär
  • 1,720
  • 3
  • 22
  • 33
  • 1
    True but not ultimately important. They will all be released after about 30s and will not prevent a restart of the service. All he really cares about is being able to restart the service and immediately bind to the same port. – Peter Wone Sep 04 '13 at 05:43