public void SendFile(string addr, string filepath) { //aSocket?.Cancel(); //string filename = Path.GetFileName(filepath); Message meta = Message.CreateMeta(filepath, PackSize); string status = ""; long continueId = 0; try { status = "Wait Confirmation"; IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(addr), ReceiverPort); UdpSend(remoteEP, meta); remoteEP.Address = IPAddress.Any; UdpReceive(ref remoteEP, msg => msg.Type == MsgType.Continue, msg => continueId = msg.PackID); if (continueId == -1) { OnTransferError?.Invoke(new State(ActionCode.FileSend, StateCode.Error, "Request rejected")); return; } remoteEP.Port = TransferPort; status = "Transferring"; TcpSetupStream(remoteEP, ns => { using FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read); byte[] bs = null; Message dataMsg = new Message { PackID = continueId, Data = new byte[PackSize] }; fs.Seek((continueId - 1) * PackSize, SeekOrigin.Begin); while (fs.Length - fs.Position > PackSize) { fs.Read(dataMsg.Data, 0, PackSize); bs = dataMsg.ToBytes(); ns.Write(bs, 0, bs.Length); ns.Flush(); dataMsg.PackID++; OnPackTransfered?.Invoke((fs.Position / fs.Length)); } fs.Read(dataMsg.Data, 0, (int)(fs.Length - fs.Position)); bs = dataMsg.ToBytes(); ns.Write(bs, 0, bs.Length); ns.Flush(); }); OnTransferDone?.Invoke(new State(ActionCode.FileSend, StateCode.Success, "")); } catch (OperationCanceledException) { OnTransferError?.Invoke(new State(ActionCode.FileSend, StateCode.Error, status + " Timeout")); } catch (SocketException e) { OnTransferError?.Invoke(new State(ActionCode.FileSend, StateCode.Error, e.Message)); } }