我有一个使用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 比某些某些语言要慢得多,这可能是原因吗?
答案 0 :(得分:3)
我不知道为什么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
注意::您的应用必须以管理权限运行,
HttpListener
才能正常工作。