title: How do I reuse a TCP endpoint address with .Net sockets
body: <p>I have some client-server socket code that I want to be able to construct and (re)connect to periodically the same endpoint address: <code>localhost:17999</code></p>
  
  <p>Here is the server:</p>
  
  <pre><code>// Listen for a connection:
  IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Loopback, 17999);             
  Socket listener = new Socket(IPAddress.Loopback.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  listener.Bind(localEndPoint);
  listener.Listen(1);
  
  // Accept the connection and send a message:
  Socket handler = listener.Accept();
  byte[] bytes = new byte[1024];
  bytes = Encoding.ASCII.GetBytes("The Message...");                 
  handler.Send(bytes);
  
  // Clean up
  handler.Shutdown(SocketShutdown.Both);
  handler.Close();
  handler.Dispose();
  
  listener.Shutdown(SocketShutdown.Both);
  listener.Close();
  listener.Dispose();
  </code></pre>
  
  <p>And here is the client:</p>
  
  <pre><code>byte[] bytes = new byte[1024];
  Socket receiver = new Socket(IPAddress.Loopback.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  receiver.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  receiver.Connect(new IPEndPoint(IPAddress.Loopback, 17999));
  
  int num_bytes_received = receiver.Receive(bytes);
  string result = Encoding.ASCII.GetString(bytes, 0, num_bytes_received);
  
  receiver.Shutdown(SocketShutdown.Both);
  receiver.Close();
  receiver.Dispose();
  </code></pre>
  
  <p>When I create the client and server for the first time, it works fine. However when I create it again, I get an error:</p>
  
  <blockquote>
    <p>"A request to send or receive data was disallowed because the socket is
    not conne cted and (when sending on a datagram socket using a sendto
    call) no address was supplied"</p>
  </blockquote>
  
  <p>I would like to be able to spin up this mechanism arbitrarily whenever I need to with the following order of events:</p>
  
  <ol>
  <li>Launch the server and wait to accept a connection</li>
  <li>Launch the client and connect to the server</li>
  <li>Accept the client connection at the server</li>
  <li>Send a message to the client</li>
  <li>Repeat when necessary </li>
  </ol>
  
  <p>How can I do this?</p>
  
  <p>Thx in Advance!</p>
  
  <p><strong>EDIT:</strong> Each time I build the client and server objects it is from a different process.</p>