【问题标题】:How to cancel TCP file transfer c#如何取消TCP文件传输c#
【发布时间】:2023-03-10 05:00:01
【问题描述】:

我有一个接收方和发送方客户端,可以传输文件。这是我目前在接收器上所拥有的:

    Thread t1;
    int flag = 0;
    string receivedPath;
    public delegate void MyDelegate(string s);
    int bytesRead = 0;
    bool endReceive = false;
        public Form1()
        {
            t1 = new Thread(new ThreadStart(StartListening));
            t1.Start();
            InitializeComponent();
        }

        public class StateObject
        {
             // Client socket.
             public Socket workSocket = null;

             public const int BufferSize = 1024*100;

             // Receive buffer.
             public byte[] buffer = new byte[BufferSize];
        }

    public static ManualResetEvent allDone = new ManualResetEvent(false);

    public void StartListening()
    {
        byte[] bytes = new Byte[1024*1000];
        IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 9050);
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            listener.Bind(ipEnd);
            listener.Listen(100);
            while (true)
            {
                allDone.Reset();
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                allDone.WaitOne();

                if (endReceive)
                {
                    listener.Disconnect(true);
                }
            }
        }           
        catch (Exception ex)
        {

        }

   }
   public void AcceptCallback(IAsyncResult ar)
   {

        allDone.Set();
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);
        StateObject state = new StateObject();
        state.workSocket = handler;
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
        new AsyncCallback(ReadCallback), state);            
        flag = 0;
   }

   public void ReadCallback(IAsyncResult ar)
    {
        int fileNameLen = 1;
        String content = String.Empty;
        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;

        try
        {
             bytesRead= handler.EndReceive(ar);

        }
        catch (SocketException x)
        {
            MessageBox.Show("File Transfer was cancelled");
            Invoke(new MyDelegate(LabelWriter), new object[] { "Waiting for connections" });
            if (File.Exists(receivedPath))
            {                    
                File.Delete(receivedPath);
                return;
            }
        }
        if (endReceive)
        {
            handler.Disconnect(true);
            if (File.Exists(receivedPath))
            {
                File.Delete(receivedPath);
            }
            return;
        }

        if (bytesRead > 0)
        {
            if (flag == 0)
            {                    
                fileNameLen = BitConverter.ToInt32(state.buffer, 0);
                string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);                     
                receivedPath = fileName;                    
                Invoke(new MyDelegate(LabelWriter), new object[] { "Receiving File: " + fileName });
                flag++;
            }
                if (flag >= 1)
                {

                    BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
                    if (flag == 1)
                    {
                        writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen));
                        flag++;
                        ReleaseMemory();
                    }
                    else
                        writer.Write(state.buffer, 0, bytesRead);
                        writer.Close();
                        try
                        {
                            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                                new AsyncCallback(ReadCallback), state);
                        }
                        catch (SocketException exc)
                        {
                            MessageBox.Show("File Transfer was cancelled");
                            Invoke(new MyDelegate(LabelWriter), new object[] { "Waiting for connections" });
                            if (File.Exists(receivedPath))
                            {                                    
                                File.Delete(receivedPath);
                                return;
                            }
                        }                                                  
                }
        }
        else            
           Invoke(new MyDelegate(LabelWriter), new object[] {"Data Received"});           
    }

我想要实现的是在传输发生时取消传输的能力。我想到的是将布尔值“EndReceive”设置为false,每次调用ReadCallBack方法时,都会检查EndReceive。如果它是假的,我断开套接字。它可以停止接收文件,但是,发送方应用程序只是冻结。这基本上是我发送的方式:

 while (true)
        {
            int index = 0;
            while (index < fs.Length)
            {
                int bytesRead = fs.Read(fileData, index, fileData.Length - index);
                if (bytesRead == 0)
                {
                    break;
                }

                index += bytesRead;
            }
            if (index != 0)
            {
                try
                {
                    clientSock.Send(fileData, index, SocketFlags.None);
                }
                catch (Exception sexc)
                {
                    MessageBox.Show("Transfer Cancelled");
                    return;
                }
                ReleaseMemory();
                if ((progressBar1.Value + (1024 * 1000)) > fs.Length)
                {
                    progressBar1.Value += ((int)fs.Length - progressBar1.Value);
                }
                else
                    progressBar1.Value += (1024 * 1000);

                lblSent.Text = index.ToString();
            }

            if (index != fileData.Length)
            {
                ReleaseMemory();
                progressBar1.Value = 0;
                clientSock.Close();
                fs.Close();                   
                break;


            } 
        }

有什么想法吗?

【问题讨论】:

  • 如果我没记错的话,如果你没有正确关闭连接,你会看到你一直在接收,但都是 0 字节。我之前做过一个应用程序,如果连接丢失,客户端将自动重新连接。因此,当连接丢失时,我将收到 0 个字节,所以此时,我只需关闭客户端,然后重新建立连接。

标签: c# file tcp transfer


【解决方案1】:

我认为很难为您正在执行的批量传输强制中断并仅使用 TCP 干净地关闭它。如果您将块大小设为 1024,并且在每个 kB 传输后,从接收方向发送方发送一个快速 ack 或 nack 字节会怎样? Nack表示要中断传输,ack表示继续。

不幸的是,这需要接收器/发送器的全双工,请小心!即使它是异步 IO,如果您计划从同一个套接字读取和写入,您确实需要在不同的线程上调用 BeginReceive 和 BeginSend。

【讨论】:

    猜你喜欢
    • 2018-05-14
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    相关资源
    最近更新 更多