private void connectToServer() { server.serverPort.setOnDataReceivedCallback( new RServer.DataReceived( (RServer sender, CommunicationNetworkStream stream, String data) => { switch (CommandRecognization.Recognize(data)) { case ExchangeType.FS_LIST_DRIVE_RESPONSE: #region "DRIVE RESPONSE" r.DrivesInformationResponse divResponse = FileSystem.ReadDriveList(stream); Invoke(new UpdateData(() => { addressBox.Text = server.nickName; //CHENGE THE ADDRESS BAR TO NICK NAME contentView.LargeImageList = driveImageList; //SET THE IMAGE LIST AS DRIVE-FILE contentView.SmallImageList = driveImageList; //SET THE IMAGE LIST AS DRIVE-FILE contentView.BeginUpdate(); })); //FREZZE UI UPDATE ListViewGroup internalGroup = new ListViewGroup("Internal Drives"); ListViewGroup removeableUSBGroup = new ListViewGroup("USB Drives"); ListViewGroup removeableCDGroup = new ListViewGroup("CD Drives"); try { foreach (r.DrivesInformationResponse.DriveInfo div in divResponse.Drives) { ListViewItem liv = new ListViewItem($"{div.VolumeLabel} ({div.Name})"); liv.Tag = div; //TAG DRIVE switch (div.DriveType) { case System.IO.DriveType.CDRom: liv.Group = removeableCDGroup; liv.ImageIndex = 1; break; case System.IO.DriveType.Fixed: liv.Group = internalGroup; liv.ImageIndex = 0; break; case System.IO.DriveType.Removable: liv.Group = removeableUSBGroup; liv.ImageIndex = 2; break; case System.IO.DriveType.Unknown: liv.ImageIndex = 3; break; } if (div.isReady) { double fill = (double)div.AvailableFreeSpace / div.TotalSize; liv.Text += $" [{(fill * 100).ToString("00.00")}%]"; } else { liv.Text += $" [NOT READY]"; } Invoke(new UpdateData(() => { contentView.Items.Add(liv); })); //UPDATE CONTENTS } } catch (Exception) { } Invoke(new UpdateData(() => { contentView.Groups.AddRange(new ListViewGroup[] { internalGroup, removeableUSBGroup, removeableCDGroup }); contentView.EndUpdate(); })); //RESUME UI UPDATE #endregion "DRIVE RESPONSE" break; case ExchangeType.FS_LIST_DIRECTORY_RESPONSE: #region "DIRECTORY RESPONSE" r.DirectoryInformationResponse dirResponse = FileSystem.ReadDirectoryList(stream); Invoke(new UpdateData(() => { contentView.LargeImageList = dirFileImageList; //SET THE IMAGE LIST AS DIRECTORY-FILE contentView.SmallImageList = dirFileImageList; //SET THE IMAGE LIST AS DIRECTORY-FILE contentView.BeginUpdate(); })); //FREEZE UI UPDATE try { foreach (r.DirectoryInformationResponse.DirectoryInfo dir in dirResponse.DirectoryList) { ListViewItem liv = new ListViewItem($"{dir.Name}"); liv.Tag = dir; //TAG DIRECTORY //ICON if (dirFileImageList.Images.ContainsKey($"|{dir.Name.ToLower()}")) { liv.ImageKey = $"|{dir.Name}"; } else { liv.ImageKey = "|max.folder"; //UNKNOW FILE FORMAT } Invoke(new UpdateData(() => { contentView.Items.Add(liv); })); //UPDATE UI UPDATE } } catch (Exception) { } Invoke(new UpdateData(() => { contentView.EndUpdate(); })); //RESUME CONTENTS #endregion "DIRECTORY RESPONSE" break; case ExchangeType.FS_LIST_FILE_RESPONSE: #region "FILE RESPONSE" r.FileInformationResponse fileResponse = FileSystem.ReadFileList(stream); Invoke(new UpdateData(() => { contentView.LargeImageList = dirFileImageList; //SET THE IMAGE LIST AS DIRECTORY-FILE contentView.SmallImageList = dirFileImageList; //SET THE IMAGE LIST AS DIRECTORY-FILE contentView.BeginUpdate(); })); //FREZZE UI UPDATE try { foreach (r.FileInformationResponse.FileInfo f in fileResponse.FileList) { ListViewItem liv = new ListViewItem($"{f.Name}"); liv.Tag = f; //TAG DIRECTORY //ICON if (dirFileImageList.Images.ContainsKey($">{f.Extention.ToLower()}")) { liv.ImageKey = $">{f.Extention}"; } else { liv.ImageKey = ">max.file.unknown"; //UNKNOW FILE FORMAT } Invoke(new UpdateData(() => { contentView.Items.Add(liv); })); //UPDATE UI UPDATE } } catch (Exception) { } Invoke(new UpdateData(() => { contentView.EndUpdate(); })); //RESUME CONTENTS #endregion "FILE RESPONSE" break; case ExchangeType.FS_DELETE_RESPONSE: #region "DELETE RESPONSE" string dJs = stream.ReadString(); r.DeleteResponse delResponse = r.DeleteResponse.FillFromJson(dJs); if (delResponse.ErrorMessage.Length > 0) { MessageBox.Show($"{delResponse.ErrorMessage}", "Error"); } #endregion "DELETE RESPONSE" break; case ExchangeType.FS_RENAME_RESPONSE: #region "RENAME RESPONSE" string rJs = stream.ReadString(); r.DeleteResponse renResponse = r.DeleteResponse.FillFromJson(rJs); if (renResponse.ErrorMessage.Length > 0) { MessageBox.Show($"{renResponse.ErrorMessage}", "Error"); } #endregion "RENAME RESPONSE" break; } } )); if (ImmidiatePath == null) { Invoke(new UpdateData(() => { addressBox.Text = server.nickName; refreshContent(); })); } else { Invoke(new UpdateData(() => { addressBox.Text = ImmidiatePath; refreshContent(); })); } }
private void newConnectionEstablishedCallback(NetworkServer serverObj, CommunicationNetworkStream __stream) { RServer connection = serverObj.serverPort; double _readOut = 0; int noOfFilesReceived = 0; //lock(_readOut){ } //SET UP TIMER Stopwatch totalTimer = new Stopwatch(); //TOTAL TIME totalTimer.Start(); //START TIMER Stopwatch fileTimer = new Stopwatch(); //FILE TIMER fileTimer.Start(); //START TIMER //HANDLE THE DATA RECEIVED RESPONSES connection.setOnDataReceivedCallback( new RServer.DataReceived((RServer sender, CommunicationNetworkStream stream, string data) => { switch (CommandRecognization.Recognize(data)) { case ExchangeType.FILE_TRANSFER: double calling = 1; fileTimer.Restart(); //START TIMER TransferDetails CURRENT_FILE = fileDetails[noOfFilesReceived]; //CURRENT FILE FileReceiver fR = new FileReceiver(stream).Initialize(); //TRANSFER OBJ //PROGRESS CALLBACK fR.FileReceivingProgressCallback = new FileReceiver.FileReceivingProgress( (string FileName, double progressRatio) => { try { CURRENT_FILE.progressRatio = progressRatio; ActualSizeTransfered = _readOut + CURRENT_FILE.FileLength * progressRatio; totalTimeElapsed = totalTimer.Elapsed; //UPDATE PUBLIC try { if ((calling % skeepCalls) == 0) { DownloadingProgressCallback(this, CURRENT_FILE, progressRatio, fileTimer); //PASS THE CALLBACK } } catch (Exception) { } calling++; } catch (Exception) { } }); //COMPLETION CALLBACK fR.FileReceivingCompletedCallback = new FileReceiver.FileReceivingCompleted( (string FileName) => { //DOWNLOAD COMPLETED try { _readOut += CURRENT_FILE.FileLength; ActualSizeTransfered = _readOut; noOfFilesReceived++; fileTimer.Stop(); //STOP TIMER totalTimeElapsed = totalTimer.Elapsed; //UPDATE PUBLIC try { DownloadingProgressCallback(this, CURRENT_FILE, 1.0d, fileTimer); //FORCED CALLBACK } catch (Exception) { } try { DownloadingCompletedCallback(this, CURRENT_FILE, fileTimer); //PASS THE CALLBACK } catch (Exception) { } } catch (Exception) { } }); try { //NEW RECEIVING IS STARTED FileDownloadingStartedCallback(this, CURRENT_FILE); //RECEIVING STARTED CALLBACK } catch (Exception) { } fR.StartReceiving(true); //START RECEIVING if (fileDetails.Count <= noOfFilesReceived) { //ALL DOWNLOADS COMPLETED totalTimer.Stop(); //STOP TIMER totalTimeElapsed = totalTimer.Elapsed; //UPDATE PUBLIC try { AllFileDownloadingCompletedCallback(this, sender); //ALL FILES RECEIVED } catch (Exception) { } NetworkServer.closeConnection(connection); //CLOSE CONNECTION } break; default: break; } })); //MADE ALL REQUESTS foreach (TransferDetails info in fileDetails) { new FileReceiverRequest(info.SourcePath, info.DestinationPath, connection.Stream, MyGlobal.BUFFER_SIZE).Request(); } }
private void allcoateNewConnection(RServer openServer, CommunicationNetworkStream _stream) { ChatBoxForm chatWindow = null;; //CHAT WINDOW //CHECK IF THEIR IS PORT LEFT TO ALLOCATE if (ConnectedClients.Count < ALLOCABLE_PORTS.Length) { NetworkClient client = new NetworkClient(); client.othId = Guid.NewGuid().ToString(); //ALLOCATE ID //START THE SERVER client.clientPort = new RServer(fileManagement.fileData.myIpAddress, allocateNewPort().ToString()); client.clientPort.setOnNewDeviceConnectedCallback( new RServer.NewDeviceConnected( (RServer sender, CommunicationNetworkStream stream) => { String cId = stream.ReadString(true); //WAIT TO GET ID Debug.WriteLine($"CONNECTION: {((NetworkClient)ConnectedClients[cId]).clientPort.ServerPort}:{cId}"); if (((NetworkClient)ConnectedClients[cId]).clientPort.ServerPort != sender.ServerPort) { sender.DetachClient(); } } ) ); client.clientPort.setOnDataReceivedCallback( new RServer.DataReceived( (RServer sender, CommunicationNetworkStream stream, string Data) => { switch (CommandRecognization.Recognize(Data)) { case ExchangeType.CLOSE_CONNECTION_REQUEST: closeConnection(sender); //CLOSE CONNECTION MessageBox.Show("CLOSE_CONNECTION_REQUEST"); break; case ExchangeType.FS_LIST_DRIVE_REQUEST: FileSystem.SentDriveList(stream); break; case ExchangeType.FS_LIST_DIRECTORY_REQUEST: FileSystem.SentDirectoryList(stream); break; case ExchangeType.FS_LIST_FILE_REQUEST: FileSystem.SentFileList(stream); break; case ExchangeType.FS_DELETE_REQUEST: FileSystem.ExecuteDelete(stream); break; case ExchangeType.FS_RENAME_REQUEST: FileSystem.ExecuteRename(stream); break; case ExchangeType.PROCESS_LIST_ALL_REQUEST: ProcessSystem.SentAllProcess(stream); break; case ExchangeType.PROCESS_KILL_REQUEST: ProcessSystem.ExecuteKillProcess(stream); break; case ExchangeType.PROCESS_START_REQUEST: ProcessSystem.ExecuteProcess(stream); break; case ExchangeType.FILE_TRANSFER: FileReceiver fr = new FileReceiver(stream).Initialize(); fr.StartReceiving(); break; case ExchangeType.FILE_TRANSFER_REQUEST: FileTransferRequest ft = new FileTransferRequest(stream).Initialize(); ft.StartTransfering(); Thread.Sleep(1000); break; case ExchangeType.NULL: //EXTENDED MODE int len = Data.IndexOf(':'); string command = Data; if (len > 0) { command = Data.Substring(0, len); } string arg = ""; if (len > 0) { arg = Data.Substring(len + 1); } switch (command) { case "CREATE_DIR": try { System.IO.Directory.CreateDirectory(arg); } catch (Exception) { } break; case "CHAT_START": chatWindow = new ChatBoxForm(); Invoke(new UpdateData(() => { chatWindow.client = sender; chatWindow.connectedIp = arg; chatWindow.Show(); })); break; case "CHAT_STOP": Invoke(new UpdateData(() => { if (chatWindow != null) { chatWindow.Close(); chatWindow.Dispose(); chatWindow = null; } })); closeConnection(sender); //CLOSE CONNECTION break; case "CHAT_MESSAGE": Invoke(new UpdateData(() => { if (chatWindow != null) { chatWindow.newMessage(arg); } })); break; default: break; } break; } } ) ); client.clientPort.Initialize(true); //TELL THE CLIENT TO MOVE TO A NEW PORT //INSTRUCT TO MOVE _stream.WriteString($"MOVE_TO_PORT:{client.clientPort.ServerPort}:{client.othId}"); Debug.WriteLine($"NEW_CONNECTION: new port allocated.{client.clientPort.ServerPort}:{client.othId}"); ConnectedClients.Add(client.othId, client); //REGISTER CLIENT } else { _stream.WriteString("WAIT_FOR_CONNECTION"); } //DISCONNECT THE CLIENT FORM THIS PORT openServer.DetachClient(); }