title: How do I Listen Over a Socket for Incoming Connections After the Last Connection is Closed?
body: <p>I'm setting up a socket to listen for incoming connections:</p>
  
  <pre><code>public Socket Handler;
  
  public void StartListening()
  {
      // Establish the locel endpoint for the socket
      IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Port);
  
      // Create a TCP/IP socket
      Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  
      try
      {
          // Bind the socket to the local endpoint and listen
          listener.Blocking = false;
          listener.Bind(localEndPoint);
          listener.Listen(100);
  
          // Start an asynchronous socket to listen for connections
          listener.BeginAccept( new AsyncCallback(AcceptCallback), listener);
      }
      catch (Exception e)
      {
          invokeStatusUpdate(0, e.Message);
      }            
  }
  
  private void AcceptCallback(IAsyncResult ar)
  {
      // Get the socket that handles the client request
      Socket listener = (Socket) ar.AsyncState;
      Socket handler = listener.EndAccept(ar);
      Handler = handler;
  
      // Create the state object
      StateObject state = new StateObject();
      state.workSocket = handler;
      handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  }
  </code></pre>
  
  <p>As you can see above, once a connection is made, I setup my BeginReceive callback. This works fine.</p>
  
  <p>Eventually I get to a point where I want to close the current connection and then begin listening on my socket again for an incomming connection attempt:</p>
  
  <pre><code>public void CloseNode(bool restart)
  {
      try
      {
          if (Handler != null)
          {
              Handler.Shutdown(SocketShutdown.Both);
              Handler.Close();
              Handler.Dispose();
              Handler = null;
          }
  
          if (restart)
              StartListening();
      }
      catch (Exception e)
      {
          invokeStatusUpdate(0, e.Message);
      }
  }
  </code></pre>
  
  <p>My close method takes a boolean to know if it should start listening for more incoming connections.</p>
  
  <p>The problem is that when I go back into my <code>StartListening</code> method, I get an exception on the line <code>listener.Bind(localEndPoint);</code> saying that <strong>"Only one usage of each socket address (protocol/network address/port) is normally permitted"</strong>.</p>
  
  <p>How do I go about setting up my listening to begin listening again?</p>