Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 重复信息,但不应重复';不要在任务中重复此消息_C#_Macos_Tcp_Server_Listener - Fatal编程技术网

C# 重复信息,但不应重复';不要在任务中重复此消息

C# 重复信息,但不应重复';不要在任务中重复此消息,c#,macos,tcp,server,listener,C#,Macos,Tcp,Server,Listener,请看图片中的问题。服务器启动一个新任务来接受客户端,然后在函数Handle(client)中处理它,这一切都可以正常工作,但每次它都会重复这条消息“client connecting…”,但它不应该这样做。除此消息外,不会调用任务的其他任何内容。bool Pending()为false,因此它不应该启动另一个任务 using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Th

请看图片中的问题。服务器启动一个新任务来接受客户端,然后在函数Handle(client)中处理它,这一切都可以正常工作,但每次它都会重复这条消息“client connecting…”,但它不应该这样做。除此消息外,不会调用任务的其他任何内容。bool Pending()为false,因此它不应该启动另一个任务

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebServer
{
    class WebServer
    {
        public static WebServer Server { get; private set; }

        private TcpListener _tcpListener = null;
        public CancellationTokenSource TokenSource { get; private set; }
        public CancellationToken Token { get; private set; }

        public int i = 0;

        static void Main(string[] args)
        {
            WebServer.Server = new WebServer();
        }

        WebServer()
        {
            IPAddress ipAddress;

            try
            {
                ipAddress = IPAddress.Parse("127.0.0.1");
            } catch(Exception e)
            {
                Console.WriteLine("Error while parsing ip address: " + e.Message);
                return;
            }

            _tcpListener = new TcpListener(ipAddress, 8080);
            _tcpListener.Start();

            TokenSource = new CancellationTokenSource();
            Token = TokenSource.Token;

            //Execute server
            Task.Run(() => Run());

            Console.ReadKey();
            TokenSource.Cancel();

            WaitHandle handle = Token.WaitHandle;
            handle.WaitOne();
        }

        private void Run()
        {
            Console.WriteLine("Server is runnning");
            while(!Token.IsCancellationRequested)
            {
                if(_tcpListener.Pending())
                {
                    Console.WriteLine("Pending: " + _tcpListener.Pending());
                    Task.Run(() => {
                        Console.WriteLine("Client connecting...");
                        TcpClient client = _tcpListener.AcceptTcpClient();

                        this.Handle(client);
                        return;
                    });
                }
            }
        }

        private void Handle(TcpClient client)
        {
            NetworkStream stream = client.GetStream();

            Console.WriteLine("Handling....");

            while(client.Connected)
            {
                if(stream.DataAvailable)
                {
                    Console.WriteLine("Start Reading...");
                    byte[] buffer = new byte[1024];
                    stream.Read(buffer, 0, 1024);
                    Console.WriteLine("Read: " + Encoding.ASCII.GetString(buffer));
                }

                client.Close();
            }
        }
    }
}

客户端连接不应该每次都重复,其他一切都正常

Emrah Süngü的评论似乎准确无误

TcpClient client = _tcpListener.AcceptTcpClient(); // accept first
Console.WriteLine("Client connecting...");

// then start processing in your task
Task.Run(() => this.Handle(client));
当您考虑它时,您处于一个while循环中,并且在代码实际运行之前启动了多个任务,这是非常有意义的


免责声明:这是完全未经测试的,我不对您使用此代码对他人或自己造成的伤害负责:)

我在手机上,所以我没有测试任何代码,但您在获得第一个TCPClient时(!Token),如果(_tcp…)为真,您将把一个任务排入线程池。我要强调的是,该任务尚未在threadpool上开始处理。当它开始处理时,挂起将在无限循环中为真,您将把这么多任务排入线程池,但只有一个任务将调用Handle方法(假设您只有一个客户机),因为AcceptCpcClient()是一种阻塞方法,这是您得到的另一个好方法@EmrahSüngü这是一顶可爱的帽子!:P