异步TcpServer不监听客户端输入

时间:2018-09-25 06:21:47

标签: c# asynchronous asp.net-core tcp

我目前正在TcpServer上工作,多个客户端可以同时连接到它。连接很好,我看到客户端通过服务器日志连接。但是当客户开始提供输入时,什么也没发生。

代码如下:

TcpServer.cs:

/// <summary>
/// TcpServer
/// </summary>
internal class TcpServer
{
    private readonly IConfigProvider _configProvider;
    private readonly ILoggingProvider _loggingProvider;
    private bool _accept;
    private TcpListener _listener;
    private readonly CancellationTokenSource _tokenSource;

    public TcpServer(IConfigProvider configProvider, ILoggingProvider loggingProvider)
    {
        _configProvider = configProvider;
        _loggingProvider = loggingProvider;
        _tokenSource = new CancellationTokenSource();
    }

    /// <summary>
    /// Configures the TCP server and starts the listener.
    /// </summary>
    public void Start()
    {
        try
        {
            var address = IPAddress.Parse(_configProvider.Core.ListenAddress);
            _listener = new TcpListener(address, _configProvider.Core.ListenPort);

            _listener.Start();
            _accept = true;

            _loggingProvider.LogInfo($"Listening for connections on port {_configProvider.Core.ListenPort}");
        }
        catch (Exception ex)
        {
            _loggingProvider.LogError($"Caught exception at TcpClient.StartServer(): {ex.Message}");
            _accept = false;
        }
    }

    /// <summary>
    /// Listens on the open TCP socket for new connections.
    /// </summary>
    public void Listen()
    {
        Task.Run(async () =>
        {
            if (_listener != null && _accept)
            {
                while (true)
                {
                    if (_tokenSource.Token.IsCancellationRequested)
                    {
                        _loggingProvider.LogInfo("Stopping TCP listener");
                        _accept = false;
                        _listener.Stop();
                        break;
                    }

                    var clientTask = _listener.AcceptTcpClientAsync();

                    if (clientTask.Result != null)
                    {
                        var client = clientTask.Result;

                        _loggingProvider.LogInfo($"New connection from {client.Client.RemoteEndPoint}");

                        await SessionManager.Instance.NewDescriptorAsync(client);
                    }

                    _loggingProvider.LogInfo($"Number of connected users: {SessionManager.Instance.Descriptors.Count}");
                }
            }
        }, _tokenSource.Token);
    }

    /// <summary>
    /// Stops the TCP server.
    /// </summary>
    public void Stop()
    {
        _loggingProvider.LogInfo("SHUTDOWN: Requesting cancellation of TCP listener task");
        _tokenSource.Cancel();
    }
}

SessionManager函数,称为:

/// <summary>
    /// Creates a new <see cref="Descriptor"/> from the <see cref="TcpClient"/>.
    /// </summary>
    /// <param name="client">The <see cref="TcpClient"/> to create the descriptor from.</param>
    public async Task NewDescriptorAsync(TcpClient client)
    {
        var newDescriptor = new Descriptor(client);
        Descriptors.Add(newDescriptor);            

        await newDescriptor.SendAsync("Username (new for new account): ");
    }

描述符的SendAsync函数:

/// <summary>
    /// Sends the specified message to the client.
    /// </summary>
    /// <param name="message">The message to send to the client.</param>
    public async Task SendAsync(string message)
    {
        if (!IsConnected)
        {
            return;
        }

        var bytes = Encoding.UTF8.GetBytes(message);
        await Client.GetStream().WriteAsync(bytes, 0, bytes.Length);
    }

我希望有人能帮助我。

0 个答案:

没有答案