如何让 TcpListener 接受多个连接并单独处理每个连接?

how do i get TcpListener to accept multiple connections and work with each one individually?(如何让 TcpListener 接受多个连接并单独处理每个连接?)
本文介绍了如何让 TcpListener 接受多个连接并单独处理每个连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行良好但只能接收一个连接的 SMTP 侦听器.我的 C# 代码在下面,我将它作为服务运行.我的目标是让它在服务器上运行并解析发送给它的多个 smtp 消息.

目前它解析第一条消息并停止工作.我怎样才能让它接受第二、第三、第四... SMTP 邮件并像第一个一样处理它?<​​/p>

这是我的代码:

使用系统;使用 System.Collections.Generic;使用 System.Linq;使用 System.Text;使用 System.Net.Sockets;使用 System.Net;使用 System.IO;命名空间 SMTP_Listener{课堂节目{静态无效主要(字符串 [] 参数){TcpListener listener = new TcpListener(IPAddress.Any , 8000);TcpClient 客户端;网络流 ns;listener.Start();Console.WriteLine("等待连接...");客户端 = listener.AcceptTcpClient();Console.WriteLine("已接受连接!");ns = client.GetStream();使用 (StreamWriter writer = new StreamWriter(ns)){writer.WriteLine("220 localhost SMTP 服务器就绪.");writer.Flush();使用 (StreamReader reader = new StreamReader(ns)){字符串响应 = reader.ReadLine();if (!response.StartsWith("HELO") && !response.StartsWith("EHLO")){writer.WriteLine("500 未知命令");writer.Flush();ns.关闭();返回;}字符串远程 = response.Replace("HELO", string.Empty).Replace("EHLO", string.Empty).Trim();writer.WriteLine("250 本地主机你好" + 远程);writer.Flush();响应 = reader.ReadLine();if (!response.StartsWith("MAIL FROM:")){writer.WriteLine("500 未知命令");writer.Flush();ns.关闭();返回;}remote = response.Replace("RCPT TO:", string.Empty).Trim();writer.WriteLine("250 " + remote + "我也喜欢那个人!");writer.Flush();响应 = reader.ReadLine();if (!response.StartsWith("RCPT TO:")){writer.WriteLine("500 未知命令");writer.Flush();ns.关闭();返回;}remote = response.Replace("MAIL FROM:", string.Empty).Trim();writer.WriteLine("250 " + remote + "我喜欢那个人!");writer.Flush();响应 = reader.ReadLine();if (response.Trim() != "DATA"){writer.WriteLine("500 未知命令");writer.Flush();ns.关闭();返回;}writer.WriteLine("354 输入消息.完成后,单独输入"."一行");writer.Flush();整数计数器 = 0;StringBuilder 消息 = new StringBuilder();while ((response = reader.ReadLine().Trim()) != "."){message.AppendLine(响应);计数器++;如果(计数器 == 1000000){ns.关闭();返回;//严重地?一条消息中有 100 万行?}}writer.WriteLine("250 OK");writer.Flush();ns.关闭();//将消息"插入数据库Console.WriteLine("收到消息:");Console.WriteLine(message.ToString());}}Console.ReadKey();}}}

解决方案

您可以将大部分代码分解到一个单独的线程中:

static void Main(string[] args){TcpListener listener = new TcpListener(IPAddress.Any , 8000);TcpClient 客户端;listener.Start();while (true)//在此处添加退出标志{客户端 = listener.AcceptTcpClient();ThreadPool.QueueUserWorkItem(ThreadProc, 客户端);}}私有静态无效ThreadProc(对象obj){var client = (TcpClient)obj;//在这里做你的工作}

I have an SMTP listener that works well but is only able to receive one connection. My C# code is below and I am running it as a service. My goal is to have it runnign on a server and parsing multiple smtp messages sent to it.

currently it parses the first message and stops working. how can I get it to accept the 2nd, 3rd, 4th... SMTP message and process it like it does the first?

here is my code:

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();
        }
    }
}

解决方案

You can factor out most of your code into a separate thread:

static void Main(string[] args)
{
    TcpListener listener = new TcpListener(IPAddress.Any , 8000);
    TcpClient client;
    listener.Start();

    while (true) // Add your exit flag here
    {
        client = listener.AcceptTcpClient();
        ThreadPool.QueueUserWorkItem(ThreadProc, client);
    }
}
private static void ThreadProc(object obj)
{
    var client = (TcpClient)obj;
    // Do your work here
}

这篇关于如何让 TcpListener 接受多个连接并单独处理每个连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)