应用程序需要一段时间来侦听传入连接

Application taking a while to listen for incoming connections

我有一个应用程序使用 hosts 文件来阻止某些网站。由于 hosts 文件,网站无法连接,所以效果很好,但是,我的程序应该在网站被阻止时引发事件。

我正在使用此代码:

Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim blocker As BlockListener
        Dim thread As Thread
        blocker = New BlockListener
        thread = New Thread(New ThreadStart(AddressOf blocker.listen))
        thread.Start()

    AddHandler blocker.Blocked, AddressOf User_Blocked
End Sub


Private Sub User_Blocked()
    My.Computer.Audio.Play("Sounds\Website-Blocked.wav")
    WebsiteDetected.ShowDialog()
    SetForegroundWindow(WebsiteDetected.Handle)
End Sub

Public Class BlockListener

    Private port As Integer = 80

    Private listener As TcpListener

    Private BlockUsers As Boolean = True
    Public Event Blocked As EventHandler

    Public Sub listen()
        listener = New TcpListener(IPAddress.Parse("127.0.0.1"), port)
        listener.Start()
        While (BlockUsers)
            Dim clientConnection As TcpClient = listener.AcceptTcpClient

            clientConnection.Close()
            BlockUsers = False

            RaiseEvent Blocked(Me, EventArgs.Empty)
        End While


        listener.Stop()
    End Sub

我等了一会儿(比如大约两分钟)然后程序可以检测到不良网站 被访问过,但是,我真的不想等待,因为我认为如果你只是 运行 程序会更实用,然后完成,你不必等待开始侦听传入连接的程序。

有什么方法可以更快地监听服务器?

另外,会不会是因为我的主机文件上有很多网站?我总共有 80, 000 个受感染的网站,并且由于 Visual Basic 比某些特定语言慢很多,这可能是原因吗?

我不知道为什么 TcpListener 需要这么长时间才能检测到连接,但我可以确认确实如此。

似乎解决问题的方法是改用 HttpListener,它可用于托管实际的 HTTP 服务器。

最后,您需要编组从 User_Blocked 到 UI 线程的调用,然后才能开始打开表单和访问 UI 元素。这是因为你的 Blocked 事件是 运行 在后台线程,所有 UI 相关的代码必须 运行 在 UI 线程 只有.

Private port As Integer = 80

Private listener As New HttpListener

Private BlockUsers As Boolean = True
Public Event Blocked As EventHandler

Public Sub listen()
    listener.Start()
    listener.Prefixes.Add("http://*:80/")

    While (BlockUsers)
        Dim context As HttpListenerContext = Listener.GetContext()
        context.Response.Close()

        BlockUsers = False

        RaiseEvent Blocked(Me, EventArgs.Empty)
    End While

    listener.Close()
End Sub

在您的表单中:

Private Sub User_Blocked()
    If Me.InvokeRequired Then 'Do we need to invoke or are we already on the UI thread?
        Me.Invoke(New MethodInvoker(AddressOf User_Blocked))
    Else 'We are on the UI thread.
        My.Computer.Audio.Play("Sounds\Website-Blocked.wav")
        WebsiteDetected.Show() 'Note that if you use ShowDialog(), the next line won't execute until the form has been closed.
        SetForegroundWindow(WebsiteDetected.Handle)
    End If
End Sub

NOTE: Your application must run with administrative privileges for the HttpListener to work.