我有一个应用程序,它使用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("SoundsWebsite-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("SoundsWebsite-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
注意:应用程序必须使用管理权限运行,
HttpListener
才能正常工作。