我有一個SMTP偵聽器,運行良好,但只能夠接收一個連接。我的C#代碼在下面,我正在將它作爲服務運行。我的目標是讓它在服務器上運行並解析發送給它的多個smtp消息。我如何讓TcpListener接受多個連接並單獨使用每個連接?
目前它解析第一條消息並停止工作。我怎樣才能讓它接受第二,第三,第四... SMTP消息並像第一個那樣處理它?
這裏是我的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace SMTP_Listener
{
class Program
{
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Any , 8000);
TcpClient client;
NetworkStream ns;
listener.Start();
Console.WriteLine("Awaiting connection...");
client = listener.AcceptTcpClient();
Console.WriteLine("Connection accepted!");
ns = client.GetStream();
using (StreamWriter writer = new StreamWriter(ns))
{
writer.WriteLine("220 localhost SMTP server ready.");
writer.Flush();
using (StreamReader reader = new StreamReader(ns))
{
string response = reader.ReadLine();
if (!response.StartsWith("HELO") && !response.StartsWith("EHLO"))
{
writer.WriteLine("500 UNKNOWN COMMAND");
writer.Flush();
ns.Close();
return;
}
string remote = response.Replace("HELO", string.Empty).Replace("EHLO", string.Empty).Trim();
writer.WriteLine("250 localhost Hello " + remote);
writer.Flush();
response = reader.ReadLine();
if (!response.StartsWith("MAIL FROM:"))
{
writer.WriteLine("500 UNKNOWN COMMAND");
writer.Flush();
ns.Close();
return;
}
remote = response.Replace("RCPT TO:", string.Empty).Trim();
writer.WriteLine("250 " + remote + " I like that guy too!");
writer.Flush();
response = reader.ReadLine();
if (!response.StartsWith("RCPT TO:"))
{
writer.WriteLine("500 UNKNOWN COMMAND");
writer.Flush();
ns.Close();
return;
}
remote = response.Replace("MAIL FROM:", string.Empty).Trim();
writer.WriteLine("250 " + remote + " I like that guy!");
writer.Flush();
response = reader.ReadLine();
if (response.Trim() != "DATA")
{
writer.WriteLine("500 UNKNOWN COMMAND");
writer.Flush();
ns.Close();
return;
}
writer.WriteLine("354 Enter message. When finished, enter \".\" on a line by itself");
writer.Flush();
int counter = 0;
StringBuilder message = new StringBuilder();
while ((response = reader.ReadLine().Trim()) != ".")
{
message.AppendLine(response);
counter++;
if (counter == 1000000)
{
ns.Close();
return; // Seriously? 1 million lines in a message?
}
}
writer.WriteLine("250 OK");
writer.Flush();
ns.Close();
// Insert "message" into DB
Console.WriteLine("Received message:");
Console.WriteLine(message.ToString());
}
}
Console.ReadKey();
}
}
}
爲什麼不使用'BeginAcceptTcpClient'?在這樣一個非常簡單的例子中,它是沒有必要的,但如果有GUI,異步'BeginAcceptTcpClient'將會避免凍結。 – i486 2017-09-18 09:28:47