Example #1
0
        private async void BeginAnnounceAsync()
        {
            var model = new AnnounceModel
            {
                Id       = Guid.NewGuid(),
                Sender   = Environment.MachineName,
                Filename = Path.GetFileName(FilePath),
                FileSize = new FileInfo(FilePath).Length,
                Port     = _port
            };
            var jsonModel  = JsonConvert.SerializeObject(model);
            var rawModel   = Encoding.Unicode.GetBytes(jsonModel);
            var ipEndPoint = new IPEndPoint(IPAddress.Broadcast, Port);

            try
            {
                while (true)
                {
                    await _udpClient.SendAsync(rawModel, rawModel.Length, ipEndPoint);

                    await Task.Delay(700);
                }
            }
            catch (ObjectDisposedException)
            {
            }
        }
Example #2
0
        public override int Run()
        {
            var        waitForFile    = true;
            IPEndPoint remoteEndPoint = null;

            while (waitForFile)
            {
                var received = _udpClient.ReceiveAsync().Result;
                var rawText  = Encoding.Unicode.GetString(received.Buffer);
                _model = JsonConvert.DeserializeObject <AnnounceModel>(rawText);
                if (_rejectedFiles.Contains(_model.Id))
                {
                    continue;
                }

                remoteEndPoint = received.RemoteEndPoint;
                var sender = _model.Sender ?? Dns.GetHostEntryAsync(remoteEndPoint.Address).Result.HostName;

                var accepted = _acceptFileCallback(_model.Filename, _model.FileSize, sender, remoteEndPoint.Address);
                if (accepted)
                {
                    waitForFile = false;
                }
                else
                {
                    _rejectedFiles.Add(_model.Id);
                }
            }

            if (FilePath == null)
            {
                FilePath = _model.Filename;
            }
            using (var tcpClient = new TcpClient())
            {
                tcpClient.ConnectAsync(remoteEndPoint.Address, _model.Port).Wait();
                try
                {
                    using (var stream = tcpClient.GetStream())
                    {
                        var code = SendAccept(stream);
                        if (code != ExitCodes.Ok)
                        {
                            return(code);
                        }

                        code = ReceiveFile(stream);
                        return(code);
                    }
                }
                catch (IOException e)
                {
                    Console.WriteLine("Can not read from remote source: " + e.Message);
                    return(ExitCodes.RemoteStreamClosed);
                }
            }
        }