如何在c#tcplistener中检测文件传输结束

时间:2018-10-25 10:39:20

标签: c# tcp file-transfer tcplistener

我想听发送给我的文件。为此,我编写了以下代码:

private void Listen()
{
    IPAddress localip = new IPAddress(new byte[] { 127,0,0,1 });
    Console.WriteLine("now listing, IP: " + localip);
    var listener = new TcpListener(new IPEndPoint(localip, 5678));
    listener.Start();
    while (true)
    {
        using (var client = listener.AcceptTcpClient())
        using (var stream = client.GetStream())
        using (var output = File.Create("result.data"))
        {
            Console.WriteLine("Client connected. Starting to receive the file");


            var buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
            Console.WriteLine("done receiving message");


        }

    }
}

}

现在这可以正常工作,但是一旦我收到文件,代码就会挂在行while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)上,而不是继续到行Console.WriteLine("done receiving message");。因此,它挂起了,而不是检测到它正在读取0个字节(因此不再满足while循环的条件)。当我尝试在调试器中检查它时,出现错误

stream.DataAvailable
Cannot evaluate expression because a native frame is on the top of the call stack.

有人知道如何解决此问题吗?

0 个答案:

没有答案