title: Socket disconnect behavior
body: <p>I have a small method I use to disable my socket that listens for incoming connections.</p>
  
  <pre><code>    /// &lt;summary&gt;
      /// Stops and disables the service
      /// &lt;/summary&gt;
      public void Disable() {
          if (Running) {
              try {
                  thread.Abort();
              }
              catch (System.Threading.ThreadAbortException) {
                  // This catch is not raised.
                  // We can simply process our closing of the socket and nullify the thread
              }
              finally {
                  socket.Close();
                  socket = null;
                  thread = null;
                  if (socket == null &amp;&amp; thread == null) {
                      m_Running = false;
                      OnDisabled(this, new EventArgs());
                  }
              }
          }
      }
  </code></pre>
  
  <p>My problem is that even after I call Close() and nullify the socket, the clients still remain connected. I ran a check using netstat -a, and it shows the clients are still connected.</p>
  
  <pre><code>TCP    127.0.0.1:2161         activate:7777          ESTABLISHED
  TCP    127.0.0.1:7777         activate:2161          ESTABLISHED
  </code></pre>
  
  <p>7777 is the port my host socket listens on. So my question is, after closing the host socket, why do the client sockets not disconnect. How do they remain connected to a socket that is null, and is no longer listenning?</p>
  
  <p><strong>Some additional info</strong></p>
  
  <pre><code>    /// &lt;summary&gt;
      /// Enables and runs the service
      /// &lt;/summary&gt;
      public void Enable() {
          if (!Running) {
              ThreadStart start = new ThreadStart(RunServiceAsync);
              thread = new Thread(start);
              thread.IsBackground = true;
              thread.Start();
              m_Running = true;
              OnEnabled(this, new EventArgs());
          }
      }
  </code></pre>
  
  <p>The above method is how the thread is created. Everything works fine, the threading, connections; the only issue is when I close the socket (host), and nullify it the clients are still connected to it.</p>
  
  <p><em>The question is, once the host socket is closed and set to null, what are the clients connected to? Shouldn't they disconnect and lose connection to the host, because the host socket is closed?</em></p>
  
  <p><strong>Here is the full code to help</strong></p>
  
  <pre><code>// *********************************************************************
  </code></pre>
  
  <p>// [DCOM Productions]
  // [Copyright (C) DCOM Productions All rights reserved.]
  // <strong><em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**</strong></p>
  
  <p>namespace CipherBox.Drivers {
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading;
      using System.Net.Sockets;
      using System.Net;
      using System.ComponentModel;
      using CipherBox.Objects;</p>
  
  <pre><code>/// &lt;summary&gt;
  /// Driver that manages the network connection between the master program and clients, also provides informational events
  /// &lt;/summary&gt;
  public class NetworkDriver : IDriver {
  
      #region Fields
  
      private Socket socket;
      private Thread thread;
  
      #endregion
  
      #region Properties
  
      private int m_Port = 7777;
      /// &lt;summary&gt;
      /// Gets the port that the network runs on. The default port is 7777. 
      /// &lt;/summary&gt;
      public int Port {
          get {
              return m_Port;
          }
      }
  
      #endregion
  
      #region Events
  
      /// &lt;summary&gt;
      /// Delegate for when a node connects to the service
      /// &lt;/summary&gt;
      public delegate void NodeConnectedEventHandler(object sender, NetworkNodeEventArgs e);
      /// &lt;summary&gt;
      /// Triggers when an node connects to the service
      /// &lt;/summary&gt;
      public event NodeConnectedEventHandler NodeConnected;
      /// &lt;summary&gt;
      /// Event callback for NodeConnected
      /// &lt;/summary&gt;
      private void OnNodeConnected(object sender, NetworkNodeEventArgs e) {
          if (NodeConnected != null) {
              foreach (NodeConnectedEventHandler handler in NodeConnected.GetInvocationList()) {
                  ISynchronizeInvoke syncInvoke = handler.Target as ISynchronizeInvoke;
                  if (syncInvoke != null &amp;&amp; syncInvoke.InvokeRequired) {
                      syncInvoke.Invoke(handler, new object[] { handler.Target, e });
                  }
                  else {
                      NodeConnected(this, e);
                  }
              }
          }
      }
  
      /// &lt;summary&gt;
      /// Delegate for when a node disconnects from the service
      /// &lt;/summary&gt;
      public delegate void NodeDisconnectedEventHandler(object sender, NetworkNodeEventArgs e);
      /// &lt;summary&gt;
      /// Triggers when an node disconnects from the service
      /// &lt;/summary&gt;
      public event NodeDisconnectedEventHandler NodeDisconnected;
      /// &lt;summary&gt;
      /// Event callback for NodeDisconnected
      /// &lt;/summary&gt;
      private void OnNodeDisconnected(object sender, NetworkNodeEventArgs e) {
          if (NodeDisconnected != null) {
              foreach (NodeDisconnectedEventHandler handler in NodeDisconnected.GetInvocationList()) {
                  ISynchronizeInvoke syncInvoke = handler.Target as ISynchronizeInvoke;
                  if (syncInvoke != null &amp;&amp; syncInvoke.InvokeRequired) {
                      syncInvoke.Invoke(handler, new object[] { handler.Target, e });
                  }
                  else {
                      NodeDisconnected(this, e);
                  }
              }
          }
      }
  
      #endregion
  
      #region Methods
  
      private NetworkNode FillNode(Socket socket) {
          StringBuilder stream = new StringBuilder();
          byte[] buffer = new byte[4096];
          int bytesReceived = -1;
          do {
              try {
                  bytesReceived = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
              }
              catch (System.Net.Sockets.SocketException) {
                  return null;
              }
              finally {
                  stream.Append(Encoding.ASCII.GetString(buffer, 0, bytesReceived));
              }
          } while (!stream.ToString().EndsWith("\r\n\r\n"));
          string[] packet = stream.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.None);
          if (packet.Length == 9) {
              if (packet[0].ToLower() == "CipherBox".ToLower()) {
                  NetworkNode node = new NetworkNode();
                  node.Domain = packet[1];
                  node.LocalIP = IPAddress.Parse(packet[2]);
                  node.MachineName = packet[3];
                  node.Platform = packet[4];
                  node.RemoteIP = IPAddress.Parse(packet[5]);
                  node.Workgroup = packet[6];
                  node.Socket = socket;
                  return node;
              }
              else {
                  return null;
              }
          }
          else {
              return null;
          }
      }
  
      private bool IsDisconnected(Socket socket) {
          bool connected = false;
          try {
              connected = !(socket.Poll(1, SelectMode.SelectRead) &amp;&amp; socket.Available == 0);
          }
          catch (System.Net.Sockets.SocketException) {
              connected = false;
          }
          return !connected;
      }
  
      private void MonitorNode(NetworkNode node) {
          ParameterizedThreadStart start = new ParameterizedThreadStart(MonitorNodeAsync);
          Thread thread = new Thread(start);
          thread.IsBackground = true;
          thread.Start(node);
      }
  
      private void MonitorNodeAsync(object obj) {
          NetworkNode node = obj as NetworkNode;
          while (Running || node != null) {
              if (IsDisconnected(node.Socket)) {
                  node.Socket.Shutdown(SocketShutdown.Both);
                  node.Socket.Close();
                  node.Socket = null;
                  OnNodeDisconnected(null, new NetworkNodeEventArgs(node));
                  return;
              }
              else {
                  Thread.Sleep(1000);
              }
          }
      }
  
      private void RunServiceAsync() {
          socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
          IPEndPoint localEP = new IPEndPoint(IPAddress.Any, Port);
          socket.Bind(localEP);
          socket.Listen(1);
          do {
              Socket client;
              try {
                  client = socket.Accept();
              }
              catch (System.Net.Sockets.SocketException) {
                  continue;
              }
              NetworkNode node = FillNode(client);
              if (node != null) {
                  OnNodeConnected(null, new NetworkNodeEventArgs(node));
                  MonitorNode(node);
              }
          } while (Running);
      }
  
      /// &lt;summary&gt;
      /// Sets the port that the network runs on
      /// &lt;/summary&gt;
      /// &lt;param name="port"&gt;The port to set&lt;/param&gt;
      public void SetPort(int port) {
          m_Port = port;
      }
  
      #endregion
  
      #region IDriver Members
  
      /// &lt;summary&gt;
      /// Triggered when the network driver is disabled
      /// &lt;/summary&gt;
      public event EventHandler&lt;EventArgs&gt;  Disabled;
      /// &lt;summary&gt;
      /// Event callback for Disabled
      /// &lt;/summary&gt;
      private void OnDisabled(object sender, System.EventArgs e) {
          if (Disabled != null) {
              foreach (EventHandler&lt;EventArgs&gt; handler in Disabled.GetInvocationList()) {
                  ISynchronizeInvoke syncInvoke = handler.Target as ISynchronizeInvoke;
                  if (syncInvoke != null &amp;&amp; syncInvoke.InvokeRequired) {
                      syncInvoke.Invoke(handler, new object[] { handler.Target, e });
                  }
                  else {
                      Disabled(this, e);
                  }
              }
          }
      }
  
      /// &lt;summary&gt;
      /// Triggered when the network driver is enabled
      /// &lt;/summary&gt;
      public event EventHandler&lt;EventArgs&gt;  Enabled;
      /// &lt;summary&gt;
      /// Event callback for Enabled
      /// &lt;/summary&gt;
      private void OnEnabled(object sender, System.EventArgs e) {
          if (Enabled != null) {
              foreach (EventHandler&lt;EventArgs&gt; handler in Enabled.GetInvocationList()) {
                  ISynchronizeInvoke syncInvoke = handler.Target as ISynchronizeInvoke;
                  if (syncInvoke != null &amp;&amp; syncInvoke.InvokeRequired) {
                      syncInvoke.Invoke(handler, new object[] { handler.Target, e });
                  }
                  else {
                      Enabled(this, e);
                  }
              }
          }
      }
  
      /// &lt;summary&gt;
      /// Stops and disables the service
      /// &lt;/summary&gt;
      public void Disable() {
          if (Running) {
              try {
                  thread.Abort();
              }
              catch (System.Threading.ThreadAbortException) {
                  // This catch is not raised.
                  // We can simply process our closing of the socket and nullify the thread
              }
              finally {
                  socket.Close();
                  socket = null;
                  thread = null;
                  if (socket == null &amp;&amp; thread == null) {
                      m_Running = false;
                      OnDisabled(this, new EventArgs());
                  }
              }
          }
      }
  
      /// &lt;summary&gt;
      /// Enables and runs the service
      /// &lt;/summary&gt;
      public void Enable() {
          if (!Running) {
              ThreadStart start = new ThreadStart(RunServiceAsync);
              thread = new Thread(start);
              thread.IsBackground = true;
              thread.Start();
              m_Running = true;
              OnEnabled(this, new EventArgs());
          }
      }
  
      private bool m_Running = false;
      /// &lt;summary&gt;
      /// Gets a System.Boolean value indicating whether the service is running or not
      /// &lt;/summary&gt;
      public bool Running {
          get {
              return m_Running;
          }
      }
  
      #endregion
  }
  </code></pre>
  
  <p>}</p>