发送文件后断开与服务器的连接

时间:2016-10-23 12:53:55

标签: c# tcp client listener sendfile

我试图将文件从TCP客户端发送到侦听器。它全部工作但在文件发送后,客户端正在与服务器断开连接。以下是我目前正在为客户使用的代码:

public static void SendFile(FileInfo file)
{
    try
    {  
        long size = file.Length;

        using (NetworkStream ns = client.GetStream())
        {
            using (FileStream Fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
            {
                int num;
                byte[] buffer = new byte[Fs.Length];
                while ((num = Fs.Read(buffer, 0, buffer.Length)) != 0)
                {
                    ns.Write(buffer, 0, num);
                }
                Fs.Close();
                ns.Close();
            }
        }

        FileInfo p_c = new FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\destfile.bin");
        p_c.Delete();
    } catch(Exception ex)
    {
    }
}

和服务器:

using (NetworkStream ns = new NetworkStream(current))
{
    using (FileStream Fs = new FileStream(full_path, FileMode.OpenOrCreate, FileAccess.Write))
    {        
        while ((RecBytes = ns.Read(RecData, 0, RecData.Length)) > 0)
        {
            Fs.Write(RecData, 0, RecBytes);
            totalrecbytes += RecBytes;
        }
        {
        Fs.Close();
        ns.Close();
        Console.WriteLine("File received. Path: {0}", full_path);
    }      
}

1 个答案:

答案 0 :(得分:0)

调用NetworkStream.Close()NetworkStream.Dispose(在using子句的末尾)将终止连接。

如果要保持套接字打开,请使用NetworkStream(Socket, bool)构造函数,并将false作为第二个参数传递。