Exemple #1
0
        private async void ClientStartButton(object sender, RoutedEventArgs e)
        {
            if (!ClientHost.isConnected)
            {
                ClientHost.registrationDone.Reset();
                await Task.Run(() => ClientHost.StartClient());
            }

            if (ClientHost.isConnected)
            {
                _Status.Content    = "Connected";
                _Status.Foreground = Brushes.Orange;

                Tell.Stop();
            }

            if (!ClientHost.isRegistred && ClientHost.isConnected)
            {
                Packet toSend = new Packet(Packet.Packettype.Registration);
                toSend.Data.Add(InputNick.Text);
                ClientHost.Send(toSend);
                ClientHost.registrationDone.WaitOne();
            }

            if (ClientHost.isRegistred && ClientHost.isConnected)
            {
                _Status.Content       = "Registered";
                _Status.Foreground    = Brushes.Green;
                _InputNick.IsEnabled  = false;
                _Input.IsEnabled      = true;
                _ServerList.IsEnabled = false;
                _Refresh.IsEnabled    = false;
                _Start.IsEnabled      = false;
            }
        }
Exemple #2
0
        public void Run_WithNullArgs_InvokesCommandDispatcher()
        {
            // Arrange
            var stubOptionParser  = new Mock <IOptionParser>();
            var listingSubOptions = new ListingSubOptions()
            {
                NameNodeUri = testNameNodeUri, FilePath = new List <string> {
                }
            };

            stubOptionParser.Setup(x => x.ParseOptions(It.IsAny <string[]>())).Returns(listingSubOptions);
            var stubClientProtocol = new Mock <IRestClientProtocol>();

            stubClientProtocol.SetupProperty(x => x.BaseUrl);
            var stubDataTransferProtocol = new Mock <IRestDataTransferProtocol>();
            var mockCommandDispatcher    = new Mock <ICommandDispatcher>();
            var stubCommandFactory       = new Mock <ICommandFactory>();

            var sut = new ClientHost(stubOptionParser.Object, stubClientProtocol.Object, stubDataTransferProtocol.Object, mockCommandDispatcher.Object, stubCommandFactory.Object);

            // Act
            sut.Run(new string[] { });

            // Assert
            mockCommandDispatcher.Verify(x => x.Dispatch(It.IsAny <ICommand>()));
            Assert.AreEqual(testNameNodeUri, stubClientProtocol.Object.BaseUrl.OriginalString);
        }
Exemple #3
0
        protected virtual void Dispatch(NetworkMessage message, ClientHost token)
        {
            try
            {
                var messageId = (uint)message.GetType().GetProperty("MessageId").GetValue(message);
                List <MethodHandler> functions = new List <MethodHandler>();
                foreach (var method in methods.ToArray())
                {
                    foreach (var attribute in method.Attributes)
                    {
                        if (attribute.MessageId == messageId && (attribute.Priority == Protocol.Enums.PacketActivityEnum.None || attribute.Priority.HasFlag(token.Activity)))
                        {
                            functions.Add(method);
                            break;
                        }
                    }
                }
                foreach (MethodHandler func in functions)
                {
                    func.Invoke(message, token);
                }
                OnMessageDispatched(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Can't dispatch message '{0}' due to exception '{1}'. (Source={2};) (Inner={3})", message.ToString(), ex.Message, ex.Source, ex.InnerException));

                return;
            }
        }
            /// <devdoc>
            ///     We delegate this to the ClientConfigurationHost. The only thing we need to do here is to
            ///     build a configPath from the ConfigurationUserLevel we get passed in.
            /// </devdoc>
            public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath,
                                                      IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams)
            {
                ConfigurationUserLevel userLevel = (ConfigurationUserLevel)hostInitConfigurationParams[0];
                string desiredConfigPath         = null;

                Host = (IInternalConfigHost)TypeUtil.CreateInstanceWithReflectionPermission(ClientConfigurationHostTypeName);

                switch (userLevel)
                {
                case ConfigurationUserLevel.None:
                    desiredConfigPath = ClientHost.GetExeConfigPath();
                    break;

                case ConfigurationUserLevel.PerUserRoaming:
                    desiredConfigPath = ClientHost.GetRoamingUserConfigPath();
                    break;

                case ConfigurationUserLevel.PerUserRoamingAndLocal:
                    desiredConfigPath = ClientHost.GetLocalUserConfigPath();
                    break;

                default:
                    throw new ArgumentException(SR.GetString(SR.UnknownUserLevel));
                }


                Host.InitForConfiguration(ref locationSubPath, out configPath, out locationConfigPath, configRoot, null, null, desiredConfigPath);
            }
Exemple #5
0
        public RobotViewModel()
        {
            this.clientHost = new ClientHost();

            this.timer.Tick += delegate { this.clientHost.RunOnce(); };
            this.timer.Start();
        }
Exemple #6
0
 /// <summary>
 /// Event fired from client thread when a chunk is written to disk.
 /// </summary>
 /// <param name="host"></param>
 /// <param name="chunkIdx"></param>
 void client_ChunkWritten(ClientHost host, int chunkIdx)
 {
     Dispatcher.BeginInvoke((Action)(() => {
         BitArray tmp = client.NAKs;
         this.pbClientProgress.UpdateProgress(tmp, chunkIdx);
     }), System.Windows.Threading.DispatcherPriority.Background);
 }
Exemple #7
0
        static void Main(string[] args)
        {
            ClientHost host = new ClientHost();

            host.BuildHost(args);

            host.GenericHost.Run();
        }
Exemple #8
0
        public override void SetHost(ClientHost host)
        {
            base.SetHost(host);

            theori.Host.StaticResources.AquireTexture("textures/theori-logo-large");
            theori.Host.StaticResources.AquireTexture("textures/audfx-text-large");

            m_curtain = new TransitionCurtain();
        }
Exemple #9
0
        BitArray GetClientNAKState(ClientHost host, TarballStreamReader tarball)
        {
            Console.WriteLine("Receiving {0} files to '{1}':", tarball.Files.Count, downloadDirectory.FullName);
            foreach (var fi in tarball.Files)
            {
                Console.WriteLine("{0,15} {1}", fi.Length.ToString("##,#"), fi.RelativePath);
            }
            Console.WriteLine();
            Console.WriteLine("{0,15} chunks @ {1,13} bytes/chunk", host.NumChunks.ToString("##,0"), host.ChunkSize.ToString("##,0"));

            this.numChunks = host.NumChunks;
            int numChunkBytes = host.NumBytes;

            nakBuf = new byte[numChunkBytes];
            for (int i = 0; i < numChunkBytes; ++i)
            {
                nakBuf[i] = 0xFF;
            }

            if (!testMode)
            {
                localStateFile.Refresh();
                if (localStateFile.Exists)
                {
                    if (localStateStream != null)
                    {
                        localStateStream.Close();
                    }
                    localStateStream = localStateFile.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
                    if (localStateStream.Length != numChunkBytes)
                    {
                        localStateStream.Close();
                        Console.Error.WriteLine("Inconsistent state file. Overwriting with new state.");
                        localStateFile.Delete();
                        localStateFile.Refresh();
                    }
                    else
                    {
                        // Read the NAK state:
                        localStateStream.Seek(0L, SeekOrigin.Begin);
                        localStateStream.Read(nakBuf, 0, numChunkBytes);
                    }
                }

                localStateFile.Refresh();
                if (!localStateFile.Exists)
                {
                    // Create a new file and allocate enough space for storing a NAK bit array:
                    localStateStream = localStateFile.Open(FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read);
                    localStateStream.SetLength(numChunkBytes);
                    localStateStream.Seek(0L, SeekOrigin.Begin);
                    localStateStream.Write(nakBuf, 0, numChunkBytes);
                }
            }

            return(new BitArray(nakBuf).Clone() as BitArray);
        }
Exemple #10
0
 public void SendToAllExcept(NetworkMessage msg, ClientHost except)
 {
     foreach (var client in m_clients)
     {
         if (client != except)
         {
             client.Send(msg);
         }
     }
 }
        public void Initialize()
        {
            configuration     = new Mock <IConfigurationRepository>();
            hostObject        = new Mock <IHostObject>();
            hostObjectFactory = new Mock <IHostObjectFactory>();
            logger            = new Mock <ILogger>();

            hostObjectFactory.Setup(f => f.CreateObject(It.IsAny <string>(), It.IsAny <ICommunication>())).Returns(hostObject.Object);

            sut = new ClientHost("net:pipe://some/address", hostObjectFactory.Object, logger.Object, PROCESS_ID, 0);
        }
 /// <inheritdoc />
 public override int GetHashCode()
 {
     unchecked {
         var hashCode = MemberId?.GetHashCode() ?? 0;
         hashCode = (hashCode * 397) ^ (ClientId?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (ClientHost?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (MemberMetadata?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (MemberAssignment?.GetHashCode() ?? 0);
         return(hashCode);
     }
 }
Exemple #13
0
        public override void SetHost(ClientHost host)
        {
            base.SetHost(host);

            theori.Host.StaticResources.AquireTexture("textures/theori-logo-large");
            theori.Host.StaticResources.AquireTexture("textures/audfx-text-large");

            host.Exited += OnExited;
            Input.Initialize();

            m_scanner.BeginSearching();
        }
        private IOperation BuildClientHostOperation()
        {
            var processId  = Process.GetCurrentProcess().Id;
            var factory    = new HostObjectFactory();
            var clientHost = new ClientHost(context.AppConfig.ClientAddress, factory, ModuleLogger(nameof(ClientHost)), processId, FIVE_SECONDS);
            var operation  = new CommunicationHostOperation(clientHost, logger);

            context.ClientHost = clientHost;
            context.ClientHost.AuthenticationToken = authenticationToken;

            return(operation);
        }
Exemple #15
0
        private void AccepteClient(Socket client)
        {
            var        newClient     = new SimpleClient(client);
            ClientHost currentClient = new ClientHost(newClient);

            currentClient.Disconnected += ClientDisconnected;

            currentClient.AddFrame(new BasicFrame());
            currentClient.Send(new HelloConnectMessage());

            m_clients.Add(currentClient);
        }
Exemple #16
0
        private IOperation BuildClientHostOperation()
        {
            const int FIVE_SECONDS = 5000;
            var       processId    = Process.GetCurrentProcess().Id;
            var       factory      = new HostObjectFactory();
            var       host         = new ClientHost(configuration.AppConfig.ClientAddress, factory, new ModuleLogger(logger, nameof(ClientHost)), processId, FIVE_SECONDS);
            var       operation    = new CommunicationHostOperation(host, logger);

            clientHost = host;
            clientHost.AuthenticationToken = authenticationToken;

            return(operation);
        }
Exemple #17
0
 private void HandleIdentificationMessage(ClientHost client, IdentificationMessage msg)
 {
     if (AuthServer.Instance.HasClientName(msg.name))
     {
         client.Send(new IdentificationErrorMessage());
         client.Dispose();
     }
     else
     {
         client.name = msg.name;
         client.Send(new IdentificationSuccesMessage());
     }
 }
Exemple #18
0
        private void bt_connect_Click(object sender, EventArgs e)
        {
            var newclient = new SimpleClient();

            client      = new ClientHost(newclient);
            client.name = tb_name.Text;
            client.AddFrame(new IdentificationFrame());
            newclient.Start(tb_IP.Text, 400);

            Thread.Sleep(500);

            if (!newclient.Runing)
            {
                MessageBox.Show("Connection Failed !");
            }
        }
        public DataConnection(ClientHost senderclient, ClientHost receiverclient)
        {
            try
            {
                this.state = State.NoInit;

                this.SenderClient = senderclient;
                this.ReceiverClient = receiverclient;
                this.state = State.AllRight;
            }
            catch (Exception ex)
            {
                Errorlog.Print(ex, this);
                this.state = State.Error;
            }
        }
            /// <summary>
            /// We delegate this to the ClientConfigurationHost. The only thing we need to do here is to
            /// build a configPath from the ConfigurationUserLevel we get passed in.
            /// </summary>
            public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath,
                                                      IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams)
            {
                ConfigurationUserLevel userLevel = (ConfigurationUserLevel)hostInitConfigurationParams[0];

                Host = TypeUtil.CreateInstance <IInternalConfigHost>(ClientConfigurationHostTypeName);

                string desiredConfigPath = userLevel switch
                {
                    ConfigurationUserLevel.None => ClientHost.GetExeConfigPath(),
                    ConfigurationUserLevel.PerUserRoaming => ClientHost.GetRoamingUserConfigPath(),
                    ConfigurationUserLevel.PerUserRoamingAndLocal => ClientHost.GetLocalUserConfigPath(),
                    _ => throw new ArgumentException(SR.UnknownUserLevel),
                };

                Host.InitForConfiguration(ref locationSubPath, out configPath, out locationConfigPath, configRoot, null, null, desiredConfigPath);
            }
Exemple #21
0
        private void SendOnEnter(object sender, KeyEventArgs e)
        {
            if (ClientHost.isRegistred && ClientHost.isConnected)
            {
                if (e.Key != Key.Enter)
                {
                    return;
                }
                else
                {
                    Packet toSend = new Packet(Packet.Packettype.Message);
                    toSend.Data.Add(Input.Text);
                    ClientHost.Send(toSend);

                    Input.Text = "";
                }
            }
        }
Exemple #22
0
        void ChunkWritten(ClientHost host, int chunkIdx)
        {
            // Acknowledge the chunk is received:
            //acks[chunkIdx] = true;

            if (!testMode)
            {
                // Update the state file:
                BitArray naks = host.NAKs.Clone() as BitArray;
                naks.CopyTo(nakBuf, 0);
                localStateStream.Seek(0L, SeekOrigin.Begin);
                localStateStream.Write(nakBuf, 0, nakBuf.Length);
                localStateStream.Flush();
            }

            lastWrittenChunk = chunkIdx;

            RenderProgress(host, false);
        }
Exemple #23
0
        private static async void ClientEvent(ClientHost host, Address address)
        {
            var peer = await host.ConnectAsync(address);

            using (var sPacket = new Packet("0123456789".ToByteArray(), PacketFlags.Reliable))
            {
                peer.Send(0, sPacket);
            }

            using (var rPacket = await peer.ReceiveAsync())
            {
                Logger.Debug(rPacket.Bytes.ToStr());
                CollectionAssert.AreEqual("9876543210".ToByteArray(), rPacket.Bytes);
            }

            await peer.DisconnectAsync();

            host.Stop();
        }
Exemple #24
0
        void ChunkWritten(ClientHost host, int chunkIdx)
        {
            // Acknowledge the chunk is received:
            //acks[chunkIdx] = true;

            if (!testMode)
            {
                // Update the state file:
                BitArray naks = host.NAKs.Clone() as BitArray;
                naks.CopyTo(nakBuf, 0);
                localStateStream.Seek(0L, SeekOrigin.Begin);
                localStateStream.Write(nakBuf, 0, nakBuf.Length);
                localStateStream.Flush();
            }

            lastWrittenChunk = chunkIdx;

            RenderProgress(host, false);
        }
Exemple #25
0
        public virtual void Enqueue(NetworkMessage message, ClientHost token = null, bool executeIfCan = false)
        {
            if (IsInDispatchingContext())
            {
                Dispatch(message, token);
            }
            else
            {
                lock (messageEnqueuedEvent)
                {
                    messagesToDispatch[PriorityPacket.DEFAULT].Enqueue(Tuple.Create(message, token));

                    if (!dispatching)
                    {
                        messageEnqueuedEvent.Set();
                    }
                }
            }
        }
Exemple #26
0
        static void Main(string[] args)
        {
            Serialization.RegisterFileDescriptor(Proto.Client.TestMessages.ProtosReflection.Descriptor);

            Log.SetLoggerFactory(LoggerFactory.Create(builder => {
                builder.AddConsole();
                builder.SetMinimumLevel(LogLevel.Debug);
            }));
            var logger = Log.CreateLogger("Proto.Client.TestNode");

            Remote.Remote.Start("localhost", 44000);
            ClientHost.Start("localhost", 55000);
            logger.LogInformation("Remote + ClientHost Started");
            var props = Props.FromProducer(() => new EchoActor());

            Remote.Remote.RegisterKnownKind("EchoActor", props);

            RootContext.Empty.SpawnNamed(props, "EchoActorInstance");

            Console.ReadLine();
        }
Exemple #27
0
        void RunPowerShell_Loaded(object sender, RoutedEventArgs e)
        {
            InitialSessionState state = InitialSessionState.CreateDefault();

            ClientHost clientHost = new ClientHost(this);

            _runspace = RunspaceFactory.CreateRunspace(clientHost, state);

            if (_workingDirectory != null)
            {
                Environment.CurrentDirectory = _workingDirectory;
            }

            try
            {
                _runspace.Open();

                _pipeline = _runspace.CreatePipeline();

                //Command setExecutionPolicyCommand = new System.Management.Automation.Runspaces.Command("Set-ExecutionPolicy");
                //setExecutionPolicyCommand.Parameters.Add("ExecutionPolicy", "Unrestricted");
                //setExecutionPolicyCommand.Parameters.Add("Scope", "User");
                //setExecutionPolicyCommand.Parameters.Add("Force", new SwitchParameter(true));
                //_pipeline.Commands.Add(setExecutionPolicyCommand);

                _pipeline.Commands.AddScript(Command.Script);

                _pipeline.Output.DataReady += Output_DataReady;
                _pipeline.Error.DataReady  += Error_DataReady;

                _pipeline.Input.Close();
                _pipeline.InvokeAsync();
            }
            finally
            {
                Environment.CurrentDirectory = _originalDirectory;
            }
        }
Exemple #28
0
        public void ClientSendToServer()
        {
            var address = new Address {
                HostName = "127.0.0.1", Port = 8888
            };
            var clientHost = new ClientHost();
            var serverHost = new ServerHost(address);

            var serverThread = new Thread(() => serverHost.Start(10));
            var clientThread = new Thread(() => clientHost.Start(10));

            serverThread.Start();
            clientThread.Start();

            // 往client host线程增加事件,client线程连接server
            clientHost.Events += () => ClientEvent(clientHost, address);

            // 往server host线程增加事件,accept
            serverHost.Events += () => ServerEvent(serverHost);

            serverThread.Join();
            clientThread.Join();
        }
Exemple #29
0
        /// <summary>
        /// Connect to server.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClientConnect_Click(object sender, RoutedEventArgs e)
        {
            if (IsClientRunning)
            {
                MessageBox.Show(this, @"Client is already connected!", "Connect", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (String.IsNullOrEmpty(txtClientFolder.Text.Trim()))
            {
                MessageBox.Show(this, @"Please select a download location first.", "Connect", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (String.IsNullOrEmpty(txtClientConnectIP.Text.Trim()))
            {
                MessageBox.Show(this, @"Please enter a server address first.", "Connect", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // Create the download folder if it doesn't exist:
            DirectoryInfo downloadFolder = new DirectoryInfo(txtClientFolder.Text.Trim());

            if (!downloadFolder.Exists)
            {
                downloadFolder.Create();
            }

            client = new ClientHost(ZMQ.Transport.TCP, txtClientConnectIP.Text.Trim(), String.Empty, downloadFolder, false, new ClientHost.GetClientNAKStateDelegate(GetClientNAKState), 64);
            client.ChunkWritten += new Action <ClientHost, int>(client_ChunkWritten);

            // Create a new thread to run the client on and start it:
            clientThread = new Thread(new ParameterizedThreadStart(client.Run));
            clientThread.Start();
            IsClientRunning = true;
        }
 public Clone_Should(ClientHost aWebAssemblyHost) : base(aWebAssemblyHost)
 {
     ApplicationState = Store.GetState <ApplicationState>();
 }
Exemple #31
0
        void RenderProgress(ClientHost host, bool display)
        {
            lock (lineWriter)
            {
                if (numChunks == 0) return;

                int usableWidth = consoleWidth - 3;

                int blocks = numChunks / usableWidth;
                int blocksRem = numChunks % usableWidth;

                int subblocks = usableWidth / numChunks;
                int subblocksRem = usableWidth % numChunks;

                if (!display)
                {
                    if (blocks > 0) display = (DateTimeOffset.UtcNow.Subtract(lastDisplayTime).TotalMilliseconds >= 500d) || (lastChunkBlock != (lastChunkBlock = lastWrittenChunk / blocks));
                    else display = true;
                }

                if (display)
                {
                    lastDisplayTime = DateTimeOffset.UtcNow;
                    if (!wroteLegend)
                    {
                        Console.WriteLine();
                        Console.WriteLine(" '-' no chunks    '*' some chunks    '#' all chunks    'W' current writer");
                        Console.WriteLine();
                        wroteLegend = true;
                    }

                    string backup = new string('\b', consoleWidth);
                    Console.Write(backup);
            #if true
                    string spaces = new string(' ', consoleWidth - 1);
                    Console.Write(spaces);
                    Console.Write(backup);
                    // Write network receive rate:
                    WriteRate(host.NetworkRecvChunksPerMinute * (host.ChunkSize / 60));
                    // Write disk write rate:
                    WriteRate(host.DiskWriteChunksPerMinute * (host.ChunkSize / 60));
                    Console.WriteLine();
            #endif
                    Console.Write('[');

                    // We must clone due to thread-safety issues using enumerators:
                    BitArray naks = host.NAKs.Clone() as BitArray;
                    int nakI = 0;
                    //IEnumerator<bool> boolACKs = naks.Cast<bool>().Take(numChunks).GetEnumerator();
                    if (blocks > 0)
                    {
                        int lastc = 0, c = 0, subc = 0;
                        while (c < usableWidth)
                        {
                            int numBlocks = blocks;
                            lastc = c++;
                            if ((blocksRem > 0) && (subc++ >= blocksRem))
                            {
                                ++numBlocks;
                                ++c;
                                subc = 0;
                            }

                            bool allOn = true;
                            bool allOff = false;
                            for (int i = 0; (i < numBlocks) && (nakI < host.NumChunks); ++i, ++nakI)
                            {
                                bool curr = !naks[nakI];
                                allOn = allOn & curr;
                                allOff = allOff | curr;
                            }

                            for (int x = lastc; (x < c) && (c < usableWidth); ++x)
                            {
                                if ((lastWrittenChunk >= c * blocks) && (lastWrittenChunk < (c + 1) * blocks)) Console.Write('W');
                                else if (allOn) Console.Write('#');
                                else if (allOff) Console.Write('*');
                                else Console.Write('-');
                            }
                        }
                    }
                    else
                    {
                        int lastc = 0, c = 0, subc = 0;
                        for (int i = 0; i < numChunks; ++i)
                        {
                            lastc = c;
                            c += subblocks;
                            if ((subblocksRem > 0) && (subc++ >= subblocksRem))
                            {
                                ++c;
                                subc = 0;
                            }

                            if (++nakI >= host.NumChunks) break;
                            bool curr = !naks[nakI];

                            for (int x = lastc; (x < c) && (c < usableWidth); ++x)
                            {
                                if (lastWrittenChunk == i) Console.Write('W');
                                else if (curr) Console.Write('#');
                                else Console.Write('-');
                            }
                        }
                    }

                    Console.Write(']');
                }
            }
        }
Exemple #32
0
 void ChunkReceived(ClientHost host, int chunkIdx)
 {
     RenderProgress(host, false);
 }
 /// <summary>
 /// Event fired from client thread when a chunk is written to disk.
 /// </summary>
 /// <param name="host"></param>
 /// <param name="chunkIdx"></param>
 void client_ChunkWritten(ClientHost host, int chunkIdx)
 {
     Dispatcher.BeginInvoke((Action)(() => {
         BitArray tmp = client.NAKs;
         this.pbClientProgress.UpdateProgress(tmp, chunkIdx);
     }), System.Windows.Threading.DispatcherPriority.Background);
 }
 BitArray GetClientNAKState(ClientHost host, TarballStreamReader tarball)
 {
     // TODO: Copy over code from LCC to maintain resumable download state.
     return new BitArray(host.NumBytes).Not();
 }
Exemple #35
0
 public Clone_Should(ClientHost aWebAssemblyHost) : base(aWebAssemblyHost)
 {
 }
Exemple #36
0
        private void bt_connect_Click(object sender, EventArgs e)
        {
            var newclient = new SimpleClient();
            client = new ClientHost(newclient);
            client.name = tb_name.Text;
            client.AddFrame(new IdentificationFrame());
            newclient.Start(tb_IP.Text, 400);

            Thread.Sleep(500);

            if (!newclient.Runing)
                MessageBox.Show("Connection Failed !");
        }
Exemple #37
0
        BitArray GetClientNAKState(ClientHost host, TarballStreamReader tarball)
        {
            Console.WriteLine("Receiving {0} files to '{1}':", tarball.Files.Count, downloadDirectory.FullName);
            foreach (var fi in tarball.Files)
            {
                Console.WriteLine("{0,15} {1}", fi.Length.ToString("##,#"), fi.RelativePath);
            }
            Console.WriteLine();
            Console.WriteLine("{0,15} chunks @ {1,13} bytes/chunk", host.NumChunks.ToString("##,0"), host.ChunkSize.ToString("##,0"));

            this.numChunks = host.NumChunks;
            int numChunkBytes = host.NumBytes;
            nakBuf = new byte[numChunkBytes];
            for (int i = 0; i < numChunkBytes; ++i) nakBuf[i] = 0xFF;

            if (!testMode)
            {
                localStateFile.Refresh();
                if (localStateFile.Exists)
                {
                    if (localStateStream != null)
                    {
                        localStateStream.Close();
                    }
                    localStateStream = localStateFile.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
                    if (localStateStream.Length != numChunkBytes)
                    {
                        localStateStream.Close();
                        Console.Error.WriteLine("Inconsistent state file. Overwriting with new state.");
                        localStateFile.Delete();
                        localStateFile.Refresh();
                    }
                    else
                    {
                        // Read the NAK state:
                        localStateStream.Seek(0L, SeekOrigin.Begin);
                        localStateStream.Read(nakBuf, 0, numChunkBytes);
                    }
                }

                localStateFile.Refresh();
                if (!localStateFile.Exists)
                {
                    // Create a new file and allocate enough space for storing a NAK bit array:
                    localStateStream = localStateFile.Open(FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read);
                    localStateStream.SetLength(numChunkBytes);
                    localStateStream.Seek(0L, SeekOrigin.Begin);
                    localStateStream.Write(nakBuf, 0, numChunkBytes);
                }
            }

            return new BitArray(nakBuf).Clone() as BitArray;
        }
Exemple #38
0
 private bool IsSenderByUser(ClientHost obj)
 {
     return this.ReceiveData.connection.SenderID == obj.clientstatus.ReceiverPort;
 }
Exemple #39
0
        public override void SetHost(ClientHost host)
        {
            base.SetHost(host);

            host.Exited += OnExited;
        }
        /// <summary>
        /// Connect to server.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClientConnect_Click(object sender, RoutedEventArgs e)
        {
            if (IsClientRunning)
            {
                MessageBox.Show(this, @"Client is already connected!", "Connect", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (String.IsNullOrEmpty(txtClientFolder.Text.Trim()))
            {
                MessageBox.Show(this, @"Please select a download location first.", "Connect", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (String.IsNullOrEmpty(txtClientConnectIP.Text.Trim()))
            {
                MessageBox.Show(this, @"Please enter a server address first.", "Connect", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // Create the download folder if it doesn't exist:
            DirectoryInfo downloadFolder = new DirectoryInfo(txtClientFolder.Text.Trim());
            if (!downloadFolder.Exists)
            {
                downloadFolder.Create();
            }

            client = new ClientHost(ZMQ.Transport.TCP, txtClientConnectIP.Text.Trim(), String.Empty, downloadFolder, false, new ClientHost.GetClientNAKStateDelegate(GetClientNAKState), 64);
            client.ChunkWritten += new Action<ClientHost, int>(client_ChunkWritten);

            // Create a new thread to run the client on and start it:
            clientThread = new Thread(new ParameterizedThreadStart(client.Run));
            clientThread.Start();
            IsClientRunning = true;
        }