【问题标题】:Best way to send html email in C# without disrupting the TCP connection在不中断 TCP 连接的情况下用 C# 发送 html 电子邮件的最佳方法
【发布时间】:2020-10-05 16:03:39
【问题描述】:

我正在开发一个使用 TCP 连接连接到服务器的应用程序。服务器是一个在 VPS 上运行的 C# 控制台应用程序,有数千个客户端(Android 应用程序)将连接到该服务器,每个客户端每秒都会向服务器发送数十个数据包,服务器响应每个数据包.所以这是服务器上代码的一部分:

using System;
using System.Net.Mail;
using System.Threading;

namespace Server
{
    class Program
    {

        private static Thread thread;

        static void Main(string[] args)
        {
            thread = new Thread(new ThreadStart(ConsoleThread));
            thread.Start();
            // Initialize TCP and start listening for packages from clients
        }

        private static void ConsoleThread()
        {
            while (true)
            {

            }
        }

        public static void SendTestMail()
        {
            // What is the best way to do this
            SendMail("target@example.com", "Whatever", "<p>This is a test message.</p>");
        }

        public static void SendMail(string to, string subject, string html)
        {
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
            MailMessage mail = null;
            try
            {
                mail = new MailMessage("xxxx@gmail.com", to, subject, html);
                mail.IsBodyHtml = true;
                smtpClient.Port = 587;
                smtpClient.Credentials = new System.Net.NetworkCredential("username", "password");
                smtpClient.EnableSsl = true;
                smtpClient.Send(mail);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (mail != null)
                {
                    mail.Dispose();
                }
            }
        }

    }
}

有时服务器应该向客户端发送邮件。我想知道发送邮件是否有可能会中断或延迟服务器对客户端的响应?如果是,那么您对如何调用 SendMail 方法有什么建议?这是我能想到的:

public static void SendTestMail()
{
    Thread mailThread = new Thread(() => SendMail("target@example.com", "Whatever", "<p>This is a test message.</p>"));
    mailThread.Start();
}

我也想知道你对整个事情的看法。在虚拟专用服务器和许多客户端之间使用 TCP 是一个好主意(它们之间只会传输整数和字符串变量)?比如以下规格的VPS可以支持多少个客户端? CPU:4vCores 内存:4GB 硬:50GB NVMe

【问题讨论】:

    标签: c# tcp


    【解决方案1】:

    SmtpClient 支持SendAsync(),因此发送电子邮件不会阻塞您的线程。 对于一般性问题 - 您可以通过单个连接来衡量您的应用程序的资源使用情况吗?例如如果您在开发环境中运行它并与客户端连接,那么使用了多少 CPU 和 RAM?

    【讨论】:

      猜你喜欢
      • 2014-01-01
      • 2011-07-09
      • 2012-12-15
      • 2017-09-18
      • 1970-01-01
      • 2011-10-02
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多