On 2004-11-21, Terry Olsen <(E-Mail Removed)> wrote:
> I've tried the following code straight out of MSDN. But my app still blocks
> while listening. Isn't this code supposed to keep the UI responsive while
> listening? Or maybe I'm not doing it right.... any help is begged for ;-)
>
> Public Class Listener
>
> Public Event Connected(ByVal client As TcpClient)
> Public ClientConnected As New ManualResetEvent(False)
>
> Public Sub DoBeginAcceptTcpClient()
> Dim myListener As New TcpListener(IPAddress.Parse("127.0.0.1"), 23)
> myListener.Start()
> ClientConnected.Reset()
> myListener.BeginAcceptTcpClient(New AsyncCallback(AddressOf
> DoAcceptTcpClientCallback), myListener)
> ClientConnected.WaitOne()
> End Sub
>
> Public Sub DoAcceptTcpClientCallback(ByVal ar As IAsyncResult)
> Dim myListener As TcpListener = CType(ar.AsyncState, TcpListener)
> Dim client As TcpClient = myListener.EndAcceptTcpClient(ar)
> RaiseEvent Connected(client)
> ClientConnected.Set()
> End Sub
>
> End Class
>
>
Unless your DoBeginAcceptTcpClient () method is on a separate thread,
then it will block - but not at the BeginAcceptTcpClient, but at the
ClientConnected.WaitOne ().
Normally, I would start listening on a separate thread, and do something
like:
Do While Until Terminate
ClientConnected.Reset()
MyListener.BeginAccept......
ClientConnected.WaiteOne ()
Loop
This way, you can handle multiple clients, and you won't block the main
thead. When you need to kill the thread, just close the listener...
Don't ask me any specifics about TcpListener/Client - I never use them.
I always use the Socket class in System.Net.Sockets
--
Tom Shelton [MVP]