异步套接字侦听器在单独的线程上 - VB.net

时间:2010-03-26 13:37:05

标签: vb.net multithreading sockets asynchronous tcp

我正在尝试使用Microsoft的代码进行异步套接字连接。看来监听器在锁定GUI的主线程中运行。我同时是套接字连接和多线程的新手。很难让我的思绪一下子包裹着这一切。

使用的代码位于http://msdn.microsoft.com/en-us/library/fx6588te.aspx 使用此示例,如何将侦听器移动到其自己的线程?

 Public Shared Sub Main()
    ' Data buffer for incoming data.
    Dim bytes() As Byte = New [Byte](1023) {}

    ' Establish the local endpoint for the socket.
    Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
    Dim ipAddress As IPAddress = ipHostInfo.AddressList(1)
    Dim localEndPoint As New IPEndPoint(ipAddress, 11000)

    ' Create a TCP/IP socket.
    Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

    ' Bind the socket to the local endpoint and listen for incoming connections.
    listener.Bind(localEndPoint)
    listener.Listen(100)

1 个答案:

答案 0 :(得分:1)

您可以以异步方式简单地调用套接字的Main方法。您可以使用:

Call New Action(AddressOf _
                AsynchronousSocketListener.Main).BeginInvoke(Nothing, Nothing)

或:

Call New Threading.Thread(AddressOf AsynchronousSocketListener.Main).Start()

(或使用BackgroundWorker