示例#1
0
        private static void Main(string[] args)
        {
            var address = IpAddressUtils.GetLocal();
            var local   = new IPEndPoint(address, Port);

            Console.WriteLine($"Local address={local}");

            if (args.Length == 0)
            {
                Console.Write("Input the IP address of the name server: ");
                args = new[] { Console.ReadLine() ?? string.Empty };
            }

            var remoteAddress = IPAddress.Parse(args[0]);
            var remote        = new IPEndPoint(remoteAddress, Conventions.NameServerPort);

            using var connection = new Connection(local, remote);

            Console.WriteLine("Available commands: ");

            foreach (var availableCommand in AvailableCommands)
            {
                Console.WriteLine(availableCommand.Name);
            }

            while (true)
            {
                Console.Write("Enter command: ");
                var commandName = Console.ReadLine()?.Trim() ?? string.Empty;

                if (TryHandle(commandName, out var command))
                {
                    connection.Send(command);
                    var response = connection.Receive();
                    Console.WriteLine(response);

                    if (response is PayloadResponseCommand payloadResponse)
                    {
                        Console.WriteLine(payloadResponse.PayloadPath);

                        var directory = Path.GetDirectoryName(payloadResponse.PayloadPath);
                        if (!string.IsNullOrWhiteSpace(directory))
                        {
                            Directory.CreateDirectory(directory);
                        }

                        File.WriteAllBytes(payloadResponse.PayloadPath, payloadResponse.Payload);
                    }

                    if (command is ExitCommand)
                    {
                        return;
                    }
                }
                else
                {
                    Console.WriteLine("Invalid input.");
                }
            }
        }
示例#2
0
        private static void Main(string[] args)
        {
            var address = IpAddressUtils.GetLocal();

            Console.WriteLine($"Launching on {address}:{Port}...");

            var queues = StartFileServerThreads(args);

            using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            var endpoint = new IPEndPoint(address, Port);

            socket.Bind(endpoint);
            socket.Listen(1);

            Initialize();

            while (true)
            {
                using var client = socket.Accept();

                Console.WriteLine("A client has connected.");
                HandleClient(client, queues);
                Console.WriteLine("A client has disconnected.");
            }
        }
示例#3
0
    protected override void Awake()
    {
        if (!Application.isPlaying)
        {
            return;
        }

        InitSingleInstance();
        if (Instance != this)
        {
            return;
        }

        host = IpAddressUtils.GetIpAddress(AddressFamily.IPv4, NetworkInterfaceType.Wireless80211);
        NoEndpointFoundCallback = SendNoEndpointFound;
        StartHttpListener();

        this.RegisterEndpoint(gameObject, HttpMethod.Get, "api/rest/endpoints",
                              "Get currently registered endpoints",
                              SendRegisteredEndpoints);

        this.RegisterEndpoint(gameObject, HttpMethod.Get, "api/rest/songs",
                              "Get loaded songs",
                              SendLoadedSongs);

        this.RegisterEndpoint(gameObject, HttpMethod.Get, "/api/rest/hello/{name}",
                              "Say hello (path-parameter example)",
                              SendHello);
    }
示例#4
0
        private static void HandleBackup(int localPort, IPAddress remoteBackupIp, int remoteBackupPort)
        {
            var localIp = IpAddressUtils.GetLocal();
            var local   = new IPEndPoint(localIp, localPort);
            var remote  = new IPEndPoint(remoteBackupIp, remoteBackupPort);

            using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(local);
            socket.Connect(remote);

            var buffer = new byte[256000];

            socket.SendCompletelyWithEof(Array.Empty <byte>().AsSpan());
            var backupData = socket.ReceiveUntilEof(buffer).To <BackupData>();

            lock (Mutex)
            {
                _lastTree  = backupData.Tree;
                _timestamp = backupData.Timestamp ?? new Timestamp();
                if (_lastTree == null)
                {
                    return;
                }

                if (_pathBuilder.TryGetPrefixedPath(_lastTree, _lastTree.Id, out var rootPath, out _))
                {
                    if (Directory.Exists(rootPath))
                    {
                        Directory.Delete(rootPath, true);
                    }
                }

                foreach (var(id, data) in backupData.Files)
                {
                    if (!_pathBuilder.TryGetPrefixedPath(_lastTree, id, out var path, out _))
                    {
                        continue;
                    }

                    var directory = Path.GetDirectoryName(path);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    using var file = File.Create(path);
                    file.Write(data);
                    Console.WriteLine($"Loaded file with ID {id} of size {data.Length}.");
                }
            }

            Console.WriteLine("Backup finished.");
        }
示例#5
0
        public void Open(IPAddress ip)
        {
            CreateSocket(ip.AddressFamily, SocketType.Raw, ProtocolType.Icmp);

            if (!StringUtils.IsEmpty(LocalBinding))
            {
                NetworkStream.Bind(IpAddressUtils.GetBindingIPAddress(LocalBinding, ip.AddressFamily), 0);
            }

            NetworkStream.SetPeerInfo(ip, 0);
            SetActive(true);
            NetworkStream.StreamReady();
        }
示例#6
0
        public void Start()
        {
            new Thread(() =>
            {
                var buffer = new byte[32000];

                while (true)
                {
                    try
                    {
                        var localAddress = IpAddressUtils.GetLocal();
                        var local        = new IPEndPoint(localAddress, _localPort);
                        using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp)
                              {
                                  SendTimeout = 5000, ReceiveTimeout = 5000
                              };
                        socket.Bind(local);
                        Console.WriteLine($"Connecting to file server {_serverIndex + 1}...");
                        socket.Connect(_remote);
                        Console.WriteLine($"Connected to file server {_serverIndex + 1}.");

                        while (true)
                        {
                            if (!_commands.TryDequeue(out var command))
                            {
                                continue;
                            }

                            Console.WriteLine($"Sending command to the file server {_serverIndex + 1}...");
                            socket.SendCompletelyWithEof(command.ToBytes());
                            Console.WriteLine($"Waiting for a response from the file server {_serverIndex + 1}...");
                            var response = socket.ReceiveUntilEof(buffer).To <ICommand>();
                            _responses.Enqueue(response);
                            Console.WriteLine($"Synchronized with file server {_serverIndex + 1}: {response}");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Disconnected from file server {_serverIndex + 1}.");
                        Console.WriteLine(e);
                        Thread.Sleep(500);
                    }
                }
            }).Start();
        }
示例#7
0
        public void LaunchOn(int port)
        {
            new Thread(() =>
            {
                var address      = IpAddressUtils.GetLocal();
                var local        = new IPEndPoint(address, port);
                using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                socket.Bind(local);
                socket.Listen(1);

                while (true)
                {
                    try
                    {
                        using var client = socket.Accept();
                        client.ReceiveUntilEof(new byte[32]);

                        lock (_mutex)
                        {
                            var tree       = LastTree?.Clone();
                            var timeStamp  = Timestamp?.Clone();
                            var backupData = new BackupData(tree, timeStamp);

                            if (tree != null)
                            {
                                var files = GetFiles(tree);
                                backupData.Files.AddRange(files);
                            }

                            client.SendCompletelyWithEof(backupData.ToBytes());
                            Console.WriteLine($"Send backup data of {backupData.Files.Count} files.");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }).Start();
        }
示例#8
0
        private static void Main(string[] args)
        {
            HandleFallbackArgs(ref args);

            var(localPort, backupPort) = ParseLocalPorts(args);

            lock (Mutex)
            {
                _pathBuilder = new FilePathBuilder($"fs{localPort}_");
            }

            if (TryParseRemoteBackupAddress(args, out var remoteBackupIp, out var remoteBackupPort))
            {
                HandleBackup(localPort, remoteBackupIp, remoteBackupPort);
            }

            lock (Mutex)
            {
                new BackupWorker(Mutex, () => _lastTree, _pathBuilder, () => _timestamp).LaunchOn(backupPort);
            }

            var ip    = IpAddressUtils.GetLocal();
            var local = new IPEndPoint(ip, localPort);

            using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(local);

            Console.WriteLine($"File server is listening on {local}.");
            socket.Listen(1);
            using var client = socket.Accept();

            var buffer = new byte[32000];

            while (true)
            {
                var command = client.ReceiveUntilEof(buffer).To <ICommand>();
                Console.WriteLine($"Received {command}.");

                lock (Mutex)
                {
                    var statefulCommand = command as StatefulCommand;
                    if (statefulCommand != null)
                    {
                        _lastTree = statefulCommand.Root;
                    }

                    if (_lastTree == null)
                    {
                        continue;
                    }

                    Console.WriteLine(_lastTree);

                    var visitor = new CommandHandleVisitor(_lastTree, _pathBuilder);
                    command.Accept(visitor);
                    Console.WriteLine($"Handled {command}.");

                    ICommand response = visitor.Payload != null
                                                ? new PayloadResponseCommand(command, visitor.Payload, visitor.PayloadPath, _lastTree, _timestamp)
                                                : new ResponseCommand(command);
                    client.SendCompletelyWithEof(response.ToBytes());

                    if (statefulCommand != null && _timestamp.Value >= statefulCommand.Timestamp.Value - 1)
                    {
                        _timestamp = statefulCommand.Timestamp;
                    }

                    Console.WriteLine($"Sent {response}.");
                }
            }
        }