C#套接字服务器在Ubuntu(Linux)中无法正常工作

时间:2020-07-23 13:30:25

标签: c# sockets ubuntu asp.net-core .net-core

我想在asp.net核心中为套接字服务器提供工作者服务
第一次运行就可以获取客户端消息。
但是在第二次运行中,我收到了第一条客户消息,但无法收到第二条消息
当我再次重新连接时,我收到第一条客户端消息,但我无法收到第二条消息 这是在Ubuntu中发生的,我的Windows在所有运行中都完美运行
工人服务就是这样

public class DeviceConnectionWrokerService : BackgroundService
{
    private readonly TcpListener _listener;
    private bool _running = false;

    public DeviceConnectionWrokerService()
    {
        _listener = new TcpListener(IPAddress.Any, 6000);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _listener.Start();
        _running = true;
        while (!stoppingToken.IsCancellationRequested)
        {
            var client = await _listener.AcceptTcpClientAsync();
            _takeCareOfCleint(client);
        }
    }

    private async void _takeCareOfCleint(TcpClient client)
    {
        NetworkStream stream = null;
        StreamReader reader = null;

        string clientEndPoint = client.Client.RemoteEndPoint.ToString();

        try
        {
            stream = client.GetStream();
            reader = new StreamReader(stream);

            char[] buff = new char[64];

            while (_running)
            {
                Debug.WriteLine("*** Ready to read");

                int nRet = await reader.ReadAsync(buff, 0, buff.Length);

                System.Diagnostics.Debug.WriteLine("Returned: " + nRet);

                if (nRet == 0)
                {
                    System.Diagnostics.Debug.WriteLine("Socket disconnected");
                    break;
                }

                string receivedText = new string(buff);

                System.Diagnostics.Debug.WriteLine("*** RECEIVED: " + receivedText);
                Array.Clear(buff, 0, buff.Length);
            }

        }
        catch (Exception excp)
        {
            System.Diagnostics.Debug.WriteLine(excp.ToString());
        }
    }

    public override Task StopAsync(CancellationToken cancellationToken)
    {
        _listener.Stop();
        _running = false;
        return Task.CompletedTask;
    }
}

请帮助我

0 个答案:

没有答案