private void ShareButton_Click(object sender, EventArgs e) { try { if (SharingList.SelectedIndex == -1) { MessageBox.Show("select a user first!"); } else { int nElements = SharingList.SelectedIndices.Count; int index; bool IsFolder = CheckPath(); this.Hide(); for (int i = 0; i < nElements; i++) { index = SharingList.SelectedIndices[i]; Send(sourcePath, IsFolder, userCollection[index].IP); } foreach (Thread t in threadList) { t.Join(); } this.CloseForm(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); settingsForm.BeginInvoke(settingsForm.DownloadStateDelegate, new object[] { "Unable to open the file", true }); this.Close(); } }
public void Execute() { List <Thread> threadList = null; try { //listen local IP:portTCP serverTCP = new TcpListener(Dns.GetHostAddresses(Dns.GetHostName()).Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToArray()[0], PortTCP); serverTCP.Start(); //create a list of Threads threadList = new List <Thread>(); //wait for connection or for closeServerTCP while (true) { while (!serverTCP.Pending() && !closeServerTCP) { //check if there are finished thread and remove them for (int i = 0; i < threadList.Count; i++) { if (threadList[i].Join(0)) { threadList.RemoveAt(i); i--; } } //wait for 0,1 seconds Thread.Sleep(100); } if (!closeServerTCP && serverTCP.Pending()) { //received connection request TcpClient connectedSocket = serverTCP.AcceptTcpClient(); //create thread to receive file Receiver r = new Receiver(connectedSocket, AutomaticAnswer, PathDest, settingsForm); Thread t = new Thread(r.Execute); t.Start(); threadList.Add(t); } else if (closeServerTCP) { //if closeServerTCP is true exit break; } } } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { //stop listening for new client if (serverTCP != null && serverTCP.Server != null) { serverTCP.Stop(); } //wait all threads if (threadList != null) { threadList.ForEach(x => { x.Join(); }); } //say to form that you finished (finally) if (!finalClose) { settingsForm.BeginInvoke(settingsForm.CloseThreadDelegate, new object[] { Thread.CurrentThread, Utilities.ServerTCP }); } } }
private void ReceiveFile(NetworkStream stream, long fileSize, string fileName) { string filepath = null; ProgressBar progressBarForm = null; FileStream file = null; try { //set filepath filepath = string.Concat(pathDest, "\\"); filepath = string.Concat(filepath, fileName); if (File.Exists(filepath)) { //ask if the user want to replace the file or create another or cancel String message = "Do you want to overwrite file?"; String caption = "File already exist"; MessageBoxButtons buttons = MessageBoxButtons.YesNoCancel; DialogResult result = MessageBox.Show(message, caption, buttons); if (result == DialogResult.No) { //rename file int i = 1; String extension = Path.GetExtension(filepath); String filename = Path.GetFileNameWithoutExtension(filepath); String tempFilePath = filename + "(" + i + ")"; while (File.Exists(pathDest + "\\" + tempFilePath + extension)) { i++; tempFilePath = filename + "(" + i + ")"; } filepath = pathDest + "\\" + tempFilePath + extension; } else if (result == DialogResult.Cancel) { return; } } //create file file = File.Create(filepath); //set array to receive byte[] data = new byte[buffer]; int read; long totRead = 0; Stopwatch timer; int percentage = 0; String remainingSeconds = ""; //set the timer timer = new Stopwatch(); timer.Start(); int counter = -1; //create condition vatiable and mutex Object locker = new Object(); Flag isCreated = new Flag(false); Flag cancel = new Flag(false); //create form progressBarForm = new ProgressBar(isCreated, locker, cancel, "Receiving " + fileName); Task.Run(() => { progressBarForm.ShowDialog(); }); //wait until form is created lock (locker) { while (isCreated.value() == false) { Monitor.Wait(locker); } } Boolean sendingCompleted = true; //send file while (fileSize > totRead) { lock (locker) { //if the cancel button is pressed stop receiving if (cancel.value() == true) { sendingCompleted = false; break; } } //if byte to be receved are less than buffer size reset the buffer if (fileSize - totRead < buffer) { data = new byte[fileSize - totRead]; } //read data from stream read = stream.Read(data, 0, data.Length); //check if read is 0 (nothing to read or closed connection) if (read == 0) { //delete file and close connection file.Flush(); file.Close(); File.Delete(filepath); progressBarForm.BeginInvoke(progressBarForm.closeFormDelegate); settingsForm.BeginInvoke(settingsForm.DownloadStateDelegate, new object[] { "Connection interrupted by the other user", true }); return; } //write data to file file.Write(data, 0, read); totRead = totRead + read; //set remaining time and pecentage once at second if (counter < (int)timer.Elapsed.TotalSeconds) { counter = (int)timer.Elapsed.TotalSeconds; Utilities.SetPercentage(ref percentage, fileSize, totRead); Utilities.SetRemainingTime(ref remainingSeconds, timer.Elapsed, fileSize, totRead); progressBarForm.BeginInvoke(progressBarForm.percentageDelegate, new object[] { percentage }); progressBarForm.BeginInvoke(progressBarForm.timeDelegate, new object[] { new String(remainingSeconds.ToCharArray()) }); } } timer.Stop(); if (fileSize != totRead && cancel.value() == false) { //errore Console.WriteLine("ERROR - Receiver.receivefile"); } //close progressbar, send notification, flush and close fileStream (finally) progressBarForm.BeginInvoke(progressBarForm.closeFormDelegate); if (sendingCompleted) { settingsForm.BeginInvoke(settingsForm.DownloadStateDelegate, new object[] { "File received correctly", false }); } file.Flush(); file.Close(); if (!sendingCompleted) { File.Delete(filepath); } }catch (Exception ex) { //delete file and close connection if (file != null) { file.Flush(); file.Close(); File.Delete(filepath); } if (progressBarForm != null && progressBarForm.Created) { progressBarForm.BeginInvoke(progressBarForm.closeFormDelegate); } progressBarForm.BeginInvoke(progressBarForm.closeFormDelegate); throw ex; } }
public void Execute() { //if is a folder zip it and send it if (IsFolder) { try { //give a not existing name int c = 0; String zipName = Path.GetFileName(pathFile) + ".zip"; while (File.Exists(pathFile + "\\..\\" + zipName)) { c++; zipName = Path.GetFileName(pathFile) + "(" + c + ").zip"; } //create zip and change the pathFile ZipFile.CreateFromDirectory(pathFile, pathFile + "\\..\\" + zipName, CompressionLevel.Optimal, true); pathFile = pathFile + "\\..\\" + zipName; } catch (UnauthorizedAccessException) { MessageBox.Show("You do not have the permission to open the folder", "Folder permission error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } catch (DirectoryNotFoundException) { MessageBox.Show("Folder do not exist anymore", "Folder not found", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } catch (Exception e) { Console.WriteLine(e.ToString()); return; } } bool aswerDeclined = false; try { //initialize socket tcpClient = new TcpClient(); //connect to server tcpClient.Connect(endPoint.Address, endPoint.Port); //create request message int messageSize = 0; byte[] request = CreateRequestMessage(ref messageSize); //get network stream NetworkStream stream = tcpClient.GetStream(); //send request message stream.Write(request, 0, messageSize); byte[] answer = new byte[1]; // Read can return anything from 0 to numBytesToRead. if (stream.Read(answer, 0, 1) == 0) { //if no byte is read connenction is closed settingsForm.BeginInvoke(settingsForm.DownloadStateDelegate, new object[] { "Unable to send or receive message with the server", true }); tcpClient.Close(); return; } //check the answer if (answer[0] == 1) { //receiver does want the file //send the file SendFile(stream); } else { aswerDeclined = true; } } catch (Exception e) { String mx; if (e is SocketException) { mx = "Unable to connect to the server"; } else if (e is IOException) { mx = "Unable to send or receive message with the server"; } else if (e is SecurityException || e is UnauthorizedAccessException) { mx = "Unable to open the file"; } else if (e is RibbitException) { RibbitException ribbitException = (RibbitException)e; if (ribbitException.Parameter.Equals("File")) { mx = "Unable to open the file"; } else if (ribbitException.Parameter.Equals("Socket")) { mx = "Network problems, unable to send the file"; } else { mx = "Unable to send the file"; } } else { mx = "Unable to send the file"; } settingsForm.BeginInvoke(settingsForm.DownloadStateDelegate, new object[] { mx, true }); tcpClient.Close(); Console.WriteLine(e.ToString()); return; } //close connection tcpClient.Close(); //if is a folder delete the zip File if (IsFolder) { try { File.Delete(pathFile); } catch (Exception e) { Console.WriteLine(e.ToString()); } } //send notifications if (sendingCompleted) { String msg; if (aswerDeclined) { msg = "Receiver declined your file/folder"; } else { msg = "File sent correctly"; } settingsForm.BeginInvoke(settingsForm.DownloadStateDelegate, new object[] { msg, false }); } }
public void Execute() { int c = 0; Boolean repeat = true; while (repeat) { repeat = false; c++; try { //initialize UdpClient udpClient = new UdpClient(); //set end point to multicast 239.168.100.2:64537 IPEndPoint endPointUDP = new IPEndPoint(Utilities.multicastEndPoint.Address, Utilities.multicastEndPoint.Port); while (closeClientUDP == false) { //create payload: 4 byte lenght payload 4 byte port n byte name byte[] nameBytes = Encoding.UTF8.GetBytes(Name); int nameSize = nameBytes.Length; int payloadSize = nameSize + 8; byte[] payload = new byte[payloadSize]; Buffer.BlockCopy(BitConverter.GetBytes(payloadSize), 0, payload, 0, 4); //big/little endian Buffer.BlockCopy(BitConverter.GetBytes(PortTCP), 0, payload, 4, 4); Buffer.BlockCopy(nameBytes, 0, payload, 8, nameSize); if (NetworkInterface.GetIsNetworkAvailable()) { //send messagge udpClient.Send(payload, payloadSize, endPointUDP); } //sleep for 2 seconds Thread.Sleep(2000); } //close udpclient udpClient.Close(); //say to form that you finished if (!finalClose) { form.BeginInvoke(form.CloseThreadDelegate, new object[] { Thread.CurrentThread, Utilities.CientUDP }); } } catch (SocketException e) { //Console.WriteLine(e.ErrorCode); Console.WriteLine(e.ToString()); if (c < 2) { if (udpClient != null && udpClient.Client != null) { udpClient.Close(); } repeat = true; } else { //say to form that you finished if (!finalClose) { form.BeginInvoke(form.CloseThreadDelegate, new object[] { Thread.CurrentThread, Utilities.CientUDP }); } if (udpClient != null && udpClient.Client != null) { udpClient.Close(); } } } } }
public void Execute() { Thread listManager = null; try { //join muticast and listen at 64537 port udpServer = new UdpClient(Utilities.multicastEndPoint.Port); udpServer.JoinMulticastGroup(Utilities.multicastEndPoint.Address); //create thread to manage userlist listManager = new Thread(this.ListManager); listManager.Start(); //wait for data or for closeServerUDP while (true) { while (udpServer.Available == 0 && !closeServerUDP) { //wait for 0,1 seconds Thread.Sleep(100); } if (!closeServerUDP && udpServer.Available > 0) { //Datagram received and put it into temp list IPEndPoint RemoteIpEndPoint = new IPEndPoint(0, 0); byte[] data = udpServer.Receive(ref RemoteIpEndPoint); queue.Enqueue(new Tuple <byte[], IPEndPoint>(data, RemoteIpEndPoint)); newData.Set(); } else if (closeServerUDP) { //if closeServerUDP is true exit break; } } //leave multicast group and close udpclient (finally) udpServer.DropMulticastGroup(Utilities.multicastEndPoint.Address); udpServer.Close(); //close ListSetter listManager.Join(); } catch (Exception e) { Console.WriteLine(e.ToString()); //close socket if (udpServer != null && udpServer.Client != null) { udpServer.Close(); } //close listManager CloseThread(); if (listManager != null) { listManager.Join(); } //say to settingsform that you closed settingsForm.BeginInvoke(settingsForm.CloseThreadDelegate, new object[] { Thread.CurrentThread, Utilities.ServerUDP }); } }