如何用vb.net监听端口25

时间:2013-07-08 15:30:58

标签: vb.net email filter spam

我基本上是在为邮件服务器上的传入电子邮件编写垃圾邮件过滤器。我想编写一个VB.NET程序,它可以侦听端口25上的任何传入邮件,然后在其上运行我的脚本,然后将其传递给在不同端口上运行的邮件服务器。

我需要做什么才能让我的程序坐下来等待消息进入端口25然后对它作出反应?

感谢。

1 个答案:

答案 0 :(得分:0)

这里,作为一个例子,是我在一段时间以前在VB.NET中修改过的套接字监听服务的一部分。基本上,套接字在服务启动时侦听端口25上的流量,接受连接,然后将该连接分配给新线程,发送响应,然后关闭TCP连接。

Dim serverSocket As New TcpListener(IPAddress.Any, "25")
Dim ipAddress As System.Net.IPAddress = System.Net.Dns.Resolve(System.Net.Dns.GetHostName()).AddressList(0)
Dim ipLocalEndPoint As New System.Net.IPEndPoint(IPAddress, 25)

Protected Overrides Sub OnStart(ByVal args() As String)
    Dim listenThread As New Thread(New ThreadStart(AddressOf ListenForClients))
    listenThread.Start()
End Sub

Protected Overrides Sub OnStop()
    ' Add code here to perform any tear-down necessary to stop your service.
End Sub

Private Sub ListenForClients()
    serverSocket = New TcpListener(ipLocalEndPoint)
    serverSocket.Start()
    While True
        Dim client As TcpClient = Me.serverSocket.AcceptTcpClient
        Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf HandleClientComm))
        clientThread.Start(client)
    End While
End Sub

Private Sub HandleClientComm(ByVal client As Object)
    Dim tcpClient As TcpClient = DirectCast(client, TcpClient)
    Dim clientStream As NetworkStream = tcpClient.GetStream

    Dim message As Byte() = New Byte(4095) {}
    Dim bytesRead As Integer

    While True
        If (bytesRead = 0) Then
            Exit While
        End If
        Dim encoder As New asciiencoding()
        Dim serverResponse As String = "Response to send"
        'Response to send back to the testing client
        Dim sendBytes As [Byte]() = encoding.ascii.getbytes(serverResponse)
        clientStream.Write(sendBytes, 0, sendBytes.Length)
    End While
    tcpClient.Close()
End Sub