예제 #1
0
        public int recvFile(string path)
        {
            try
            {
                string fileName;


                //invio +ok al server
                //   sockClipBoard.Send(msg);
                // Console.WriteLine("Ho ricevuto F allora mando +ok mandato");


                //ricevo il nome del file
                sockClipBoard.Receive(clientData);

                // Console.WriteLine("ClientData: " + Encoding.ASCII.GetString(clientData));
                int fileNameLen = BitConverter.ToInt32(clientData, 0);

                fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
                //ricevo la dimensione
                long dim = BitConverter.ToInt64(clientData, fileNameLen + 4);
                // byte[] msg2 = Encoding.ASCII.GetBytes("+OK" + fileName);
                //Console.WriteLine("Ho ricevuto correttamente i dati del file");
                // Console.WriteLine("ClientData: " + Encoding.ASCII.GetString(clientData));
                //invio +ok al server
                sockClipBoard.Send(msg);
                // Console.WriteLine("+ok mandato");
                // Console.WriteLine("++++++++++++++ " + fileName);
                BinaryWriter bWrite = new BinaryWriter(File.Open(path + fileName, FileMode.Append));


                int  ricevuti   = 0;
                bool errorefile = false;
                long dimBar     = dim;

                Form2 form2 = new Form2();

                //
                Thread backgroundThread = new Thread(
                    new ThreadStart(() =>
                {
                    form2.SetBar(100);
                    // Iterate from 0 - 99
                    // On each iteration, pause the thread for .05 seconds, then update the dialog's progress bar
                    try
                    {
                        while (dim > 0 && !errorefile)
                        {
                            if (sockClipBoard.Poll(3000000, SelectMode.SelectRead))
                            {
                                byteRead = sockClipBoard.Receive(clientData);

                                ricevuti        = ricevuti + byteRead;
                                string response = Encoding.ASCII.GetString(clientData, 0, byteRead);

                                if (response == "-ERR\r\n")//il server mi manda -ERR quando  durante un trasferimento file
                                //                      io cambio file da mettere nella clip
                                {
                                    bWrite.Close();
                                    // Close the dialog if it hasn't been already
                                    if (form2.InvokeRequired)
                                    {
                                        form2.BeginInvoke(new Action(() => { form2.showdialogset(true); form2.Close(); form2.showdialogset(false); }));
                                    }
                                    errorefile = true;
                                    return;
                                }
                                // Console.WriteLine(dimBar);
                                // Console.WriteLine((float)((100 * byteRead) /dimBar));
                                form2.UpdateProgress(byteRead, (int)dimBar, fileName);

                                bWrite.Write(clientData, 0, byteRead);
                                dim = dim - byteRead;
                            }
                            else
                            {
                                bWrite.Close();
                                // Close the dialog if it hasn't been already
                                if (form2.InvokeRequired)
                                {
                                    form2.BeginInvoke(new Action(() => { form2.showdialogset(true); form2.Close(); form2.showdialogset(false); }));
                                }
                                errorefile = true;
                                return;
                            }
                        }
                        bWrite.Close();

                        if (form2.InvokeRequired)
                        {
                            form2.BeginInvoke(new Action(() => { form2.showdialogset(true); form2.Close(); form2.showdialogset(false); }));
                        }
                    }
                    catch (Exception ex)
                    {
                        bWrite.Close();
                        // Close the dialog if it hasn't been already
                        if (form2.InvokeRequired)
                        {
                            form2.BeginInvoke(new Action(() => { form2.showdialogset(true); form2.Close(); form2.showdialogset(false); }));
                        }
                        errorefile = true;
                        server.terminatecurrentsocket = true;
                        return;
                    }
                    // Console.WriteLine("File Ricevuto!");


                    // Reset the flag that indicates if a process is currently running
                }
                                    ));

                // Start the background process thread
                backgroundThread.Start();

                if (form2.ShowDialog() == DialogResult.OK)
                {
                    formClip.getcurrentsockinvio().Send(Encoding.ASCII.GetBytes("-ERR\r\n"));
                    errorefile = true;
                }
                backgroundThread.Join();

                if (errorefile == true)
                {
                    errorefile = false;
                    return(-1);
                }

                if (path == @"C:\local\")
                {
                    //Console.WriteLine("Sono nell if");
                    listFileName.Add(path + fileName);
                }
                sockClipBoard.Send(msg);
                return(1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("errore nella ricezione");
                return(-1);
            }
        }
        public int SendFile(string namefile)
        {
            try{
                byte[] msg      = new byte[1024];
                byte[] buffer   = new byte[1024 * 1024];
                byte[] conferma = new byte[1024];



                FileInfo f = new FileInfo(namefile);
                // Console.WriteLine("ho trovato un file di dimensione" + f.Length);
                nomefile = f.Name;
                dim      = f.Length;
                if (dim > (100 * 1024 * 1024))
                {
                    DialogResult result = MessageBox.Show("You try to copy or cut a big file bigger than 100 MB , are you sure? the operation may take a long time", "Warning",
                                                          MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                    if (result == DialogResult.Cancel)
                    {
                        return(-2);
                    }
                }
                msg = Encoding.ASCII.GetBytes("F");
                clipsocket.Send(msg);

                byte[] fileNameByte = Encoding.ASCII.GetBytes(this.nomefile);
                byte[] fileNameLen  = BitConverter.GetBytes(fileNameByte.Length);
                byte[] filedim      = BitConverter.GetBytes(this.dim);
                //   Console.WriteLine("sto creando le informazioni da mandare al client");
                byte[] clientData = new byte[4 + fileNameByte.Length + filedim.Length];
                fileNameLen.CopyTo(clientData, 0);
                fileNameByte.CopyTo(clientData, 4);
                filedim.CopyTo(clientData, 4 + fileNameByte.Length);

                clipsocket.Send(clientData);


                clipsocket.Receive(conferma);

                string confermastringa = Encoding.ASCII.GetString(conferma);
                if (confermastringa.IndexOf("+OK") > -1)
                {
                    //      Console.WriteLine(" inizio lo stream del file");

                    FileStream fileStream = new FileStream(namefile, FileMode.Open, FileAccess.Read);

                    int length = (int)fileStream.Length;  // get file length
                    // create buffer
                    int    count;
                    double d;         // actual number of bytes read
                    long   sum = dim; // total number of bytes read
                    // Thread.Sleep(100);
                    // io questo coso non è che lo abbia tanto capito.
                    if (dim > (1024 * 1024))
                    {
                        d = (((double)dim) / (double)(1024 * 1024));
                    }
                    else
                    {
                        d = 1;
                    }

                    /************************************ ISTANZIO LA FORM PER LA SEND DEL FILE *****************/
                    // questa inzialmente era fatta allocando un altro thread che si occupava di aggiornare la
                    // barra. Da rivedere è l'utilizzo della percentuale. Da mettere Lato client. Ma al ricevitore?

                    Form2 form2 = new Form2();
                    //
                    err = false;
                    erroreTrasferimento = false;
                    backgroundThread    = new Thread(
                        new ThreadStart(() =>
                    {
                        try
                        {
                            while (((count = fileStream.Read(buffer, 0, 1024 * 1024)) > 0) && !err)
                            {
                                // form2.SetBar((int)sum);
                                clipsocket.Send(buffer, count, SocketFlags.None);
                                dim = dim - count;
                                //  Console.WriteLine(dim);
                                long count2 = count;
                                form2.UpdateProgress(count, (int)sum, nomefile);

                                /*** aggiorno la progress bar***/
                            }

                            fileStream.Close();

                            // Close the dialog if it hasn't been already
                            if (form2.InvokeRequired)
                            {
                                form2.BeginInvoke(new Action(() => { form2.showdialogset(true); form2.Close(); form2.showdialogset(false); }));
                            }
                            Console.WriteLine("sto ammazzando il thread().");

                            //clipsocket.Send(Encoding.ASCII.GetBytes("-ERR\r\n"));
                            // Reset the flag that indicates if a process is currently running
                        }
                        catch (SocketException ex)
                        {
                            erroreTrasferimento = true;
                            // fileStream.Close();
                            if (form2.InvokeRequired)
                            {
                                form2.BeginInvoke(new Action(() => { form2.showdialogset(true); form2.Close(); form2.showdialogset(false); }));
                            }
                            if (clipsocket != null)
                            {
                                clipsocket.Close();
                            }
                            Console.WriteLine("sto ammazzando il thread().");
                            fileStream.Close();
                            return;
                        }
                        catch (Exception ex)
                        {
                            erroreTrasferimento = true;
                            // fileStream.Close();
                            if (form2.InvokeRequired)
                            {
                                form2.BeginInvoke(new Action(() => { form2.Close(); }));
                            }

                            Console.WriteLine("errore");
                            Console.WriteLine(ex.ToString() + ex.Message);
                        }
                    }
                                        ));

                    // Start the background process thread
                    backgroundThread.Start();

                    // form2.ShowDialog();
                    // qui sto curando il caso in cui chiudo la finestra del trasferimento.
                    // backgroundThread.Join();
                    if (form2.ShowDialog() == DialogResult.OK)
                    {
                        err = true;
                        return(-1);
                    }
                    backgroundThread.Join();
                    if (erroreTrasferimento)
                    {
                        err = true;
                        return(-1);
                    }
                }

                return(1);
            }catch (IOException ex) {
                MessageBox.Show("Devi selezionare prima un file");
                return(-1);
            }
        }