title: Socket Listen and Connect
body: <p>I setup a System.Net.Sockets.Socket. I start the socket listening for incoming connections to take socket requests. This same socket should be able to stop Listen and write and connect to other sockets. After I set the socket to Listen I cannot get it to send a connect command. I get this Exception:</p>
  
  <blockquote>
    <p>An unhandled exception of type 'System.InvalidOperationException' occurred in 
    System.dll
    Additional information: You may not perform this operation after calling the Listen method.</p>
  </blockquote>
  
  <p>How can I change its state and allow it to change connections and go back to listening? I am using TCP localhost</p>
  
  <pre><code>Public Class SocketHandler
  
  Private Socke As Sockets
  Private connectThread As Thread
  Private listenThread As Thread 
  Private listening As Boolean = False
  
  Public Sub New()
         listenThread = New Thread(Address of Listen)
         listenThread.IsBackground = True
         listenThread.Start()
  End New
  
  Private Sub Listen()
         Socke.Bind(New IPEndPoint(IPAddress.Any, Socke.Port))
         Socke.Listen(5)
         While Listening
               Dim Sock As Sockets = DirectCast(Socke.Accept(), Sockets)
               If Not Socke.Clients.Contains(Sock) Then
                    Socke.Clients.Add(Sock)
               End If
         End While
  End Sub
  
  Private Connect(ByVal sock As Sockets)
        connectThread = New Thread(Sub() Connecting(sock))
        connectThread.IsBackground = True
        connectThread.Start()
  End If
  
  Private Sub Connecting(Byval sock As Sockets)
        'Right Here is where I need to stop Listening and have the Socket connect
        Socke.Connect(sock) 'Here is where I get the Exception
        connectThread.Abort()
        'Here I need to turn the Listening back on
  End Sub
  
  Public Class Sockets : Inherits Socket
  Public Port As Integer 
  Public IPAddress As IPAddress
  Public Clients As New List(Of Sockets)
  
  Public Overloads Sub Connect(Byval sock as Sockets)
       Dim point As New IPEndPoint(DirectCast(socket.LocalEndPoint), IPEndPoint)
       connectDone.Reset()
       BeginConnect(point, AddressOf Callback, sock)
       connectDone.WaitOne()
  End Sub
  
  Private Sub Callback(ByVal r As IAsyncResult)
       EndConnect(r)
       connectDone.Set()
  End Sub
  
  End Class
  </code></pre>