0

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

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

谢谢。

4

1 回答 1

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
于 2013-07-08T17:55:58.600 回答