Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.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/6/entity-framework/4.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# 什么';这是使用TcpListener(异步)的最佳方式_C#_Sockets_Tcplistener_Tcpserver - Fatal编程技术网

C# 什么';这是使用TcpListener(异步)的最佳方式

C# 什么';这是使用TcpListener(异步)的最佳方式,c#,sockets,tcplistener,tcpserver,C#,Sockets,Tcplistener,Tcpserver,我想用TcpListener创建一个tcp服务器,但我不知道最好的解决方案是什么。 我试了三个例子。见下文 示例1 (我使用BeginAcceptTcpClient) 示例2 (我将BeginAcceptTcpClient与AutoResteEvent一起使用) 示例3 (我使用了AcceptTcpClientAsync) 我认为最好的解决方案是最后一个(例3),但我不确定。你觉得怎么样?这是我在项目中使用的代码。这是一个只接收异步服务器,但您可以在Task.Run()中根据需要修改它。我已经注

我想用TcpListener创建一个tcp服务器,但我不知道最好的解决方案是什么。 我试了三个例子。见下文

示例1 (我使用BeginAcceptTcpClient)

示例2 (我将BeginAcceptTcpClient与AutoResteEvent一起使用)

示例3 (我使用了AcceptTcpClientAsync)


我认为最好的解决方案是最后一个(例3),但我不确定。你觉得怎么样?

这是我在项目中使用的代码。这是一个只接收异步服务器,但您可以在
Task.Run()
中根据需要修改它。我已经注释掉了代码,以便您能够理解它是如何工作的

static async Task Main(string[] args)
{
    await RunServer();
}

static async Task RunServer()
{
    TcpListener Listener = new TcpListener(IPAddress.Any, YOURPORTHERE); // Set your listener
    Listener.Start(); // Start your listener

    while (true) // Permanent loop, it may not be the best solution
    {
        TcpClient Client = await Listener.AcceptTcpClientAsync(); // Waiting for a connection
        _ = Task.Run(() => { // Connection opened. Queues the specified job to run in the ThreadPool, meanwhile the server is ready to accept other connections in parallel
            try
            {
                var Stream = Client.GetStream(); // (read-only) get data bytes
                if (Stream.CanRead) // Verify if the stream can be read.
                {
                    byte[] Buffer = new byte[Client.ReceiveBufferSize]; // Initialize a new empty byte array with the data length.
                    StringBuilder SB = new StringBuilder();
                    do // Start converting bytes to string
                    {
                        int BytesReaded = Stream.Read(Buffer, 0, Buffer.Length);
                        SB.AppendFormat("{0}", Encoding.ASCII.GetString(Buffer, 0, BytesReaded));
                    } while (Stream.DataAvailable); // Until stream data is available

                    if (SB != null) // Stream data is ready and converted to string
                        // Do some stuffs
                }
            }
            catch (Exception Ex) // In case of errors catch it to avoid the app crash
            {
                ConsoleMessage.Error(Ex.ToString()); // Detailed exception
            }
        });
    }
}

请参阅msdn套接字示例。示例使用套接字,但您可以替换继承套接字的任何类,如TCPClient或TCPListener:请注意,TCPListener很旧,既有APM(BeginX/EndX)又有基于TAP的异步(XAsync)。。您可以将它们混合使用,但出于一致性的原因,您不应该在新的线程中执行操作-erm。。。为什么?没错,要点是一样的。
class Program1
  {
    private static readonly AutoResetEvent CONNECTION_WAIT_HANDLE = new AutoResetEvent(false);
    static void Main(string[] args)
    {
      var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4567);
      var listener = new TcpListener(endPoint);

      listener.Start();

      while (true)
      {
        listener.BeginAcceptTcpClient(ClientConnectedHandle, listener);
        CONNECTION_WAIT_HANDLE.WaitOne();
        CONNECTION_WAIT_HANDLE.Reset();
      }
    }

    public static void ClientConnectedHandle(IAsyncResult asyncResult)
    {
      var listener = (TcpListener)asyncResult.AsyncState;
      var client = listener.EndAcceptTcpClient(asyncResult);
      CONNECTION_WAIT_HANDLE.Set();

      DoAsync(client);
    }
  }
class Program2
  {
    static async Task Main(string[] args)
    {
      var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4567);
      var listener = new TcpListener(endPoint);

      listener.Start();

      while (true)
      {
        var client = await listener.AcceptTcpClientAsync();
        DoAsync(client);
      }
    }

    public static void AcceptTcpClient(TcpListener listener)
    {
      listener.BeginAcceptTcpClient(ClientConnected, listener);
    }

    public static void ClientConnected(IAsyncResult asyncResult)
    {
      var listener = (TcpListener)asyncResult.AsyncState;
      var client = listener.EndAcceptTcpClient(asyncResult);
      AcceptTcpClient(listener);

      DoAsync(client);
    }
  }
static async Task Main(string[] args)
{
    await RunServer();
}

static async Task RunServer()
{
    TcpListener Listener = new TcpListener(IPAddress.Any, YOURPORTHERE); // Set your listener
    Listener.Start(); // Start your listener

    while (true) // Permanent loop, it may not be the best solution
    {
        TcpClient Client = await Listener.AcceptTcpClientAsync(); // Waiting for a connection
        _ = Task.Run(() => { // Connection opened. Queues the specified job to run in the ThreadPool, meanwhile the server is ready to accept other connections in parallel
            try
            {
                var Stream = Client.GetStream(); // (read-only) get data bytes
                if (Stream.CanRead) // Verify if the stream can be read.
                {
                    byte[] Buffer = new byte[Client.ReceiveBufferSize]; // Initialize a new empty byte array with the data length.
                    StringBuilder SB = new StringBuilder();
                    do // Start converting bytes to string
                    {
                        int BytesReaded = Stream.Read(Buffer, 0, Buffer.Length);
                        SB.AppendFormat("{0}", Encoding.ASCII.GetString(Buffer, 0, BytesReaded));
                    } while (Stream.DataAvailable); // Until stream data is available

                    if (SB != null) // Stream data is ready and converted to string
                        // Do some stuffs
                }
            }
            catch (Exception Ex) // In case of errors catch it to avoid the app crash
            {
                ConsoleMessage.Error(Ex.ToString()); // Detailed exception
            }
        });
    }
}