Beispiel #1
0
        public async Task StartServer(int port, bool singleConnection)
        {
            // Create TCP listener
            var listener = new TcpSocketListener(2048);

            listener.ConnectionReceived = async (sender, args) =>
            {
                var clientSocketContext = new SimpleSocket();

                try
                {
                    // Stop listening if we accept only a single connection
                    if (singleConnection)
                        await listener.StopListeningAsync();

                    clientSocketContext.SetSocket((TcpSocketClient)args.SocketClient);

                    // Do an ack with magic packet (necessary so that we know it's not a dead connection,
                    // it sometimes happen when doing port forwarding because service don't refuse connection right away but only fails when sending data)
                    await SendAndReceiveAck(clientSocketContext.socket, MagicAck, MagicAck);

                    if (Connected != null)
                        Connected(clientSocketContext);

                    clientSocketContext.isConnected = true;
                }
                catch (Exception)
                {
                    clientSocketContext.DisposeSocket();
                }
            };

            // Start listening
            await listener.StartListeningAsync(port);
        }
        public async Task TcpSocketClient_ShouldBeAbleToConnect()
        {
            var port = PortGranter.GrantPort();
            var listener = new TcpSocketListener();
            await listener.StartListeningAsync(port);

            var sut = new TcpSocketClient();
            await sut.ConnectAsync("127.0.0.1", port);

            await listener.StopListeningAsync();

            // getting here means nothing went boom
            Assert.True(true);
        }
        public async Task StartServer(int port, bool singleConnection, int retryCount = 1)
        {
            // Create TCP listener
            var listener = new TcpSocketListener(2048);

            listener.ConnectionReceived = async (sender, args) =>
            {
                var clientSocketContext = new SimpleSocket();

                try
                {
                    // Stop listening if we accept only a single connection
                    if (singleConnection)
                        await listener.StopListeningAsync();

                    clientSocketContext.SetSocket((TcpSocketClient)args.SocketClient);

                    // Do an ack with magic packet (necessary so that we know it's not a dead connection,
                    // it sometimes happen when doing port forwarding because service don't refuse connection right away but only fails when sending data)
                    await SendAndReceiveAck(clientSocketContext.socket, MagicAck, MagicAck);

                    Connected?.Invoke(clientSocketContext);

                    clientSocketContext.isConnected = true;
                }
                catch (Exception)
                {
                    clientSocketContext.DisposeSocket();
                }
            };

            for (int i = 0; i < retryCount; ++i)
            {
                try
                {
                    // Start listening
                    await listener.StartListeningAsync(port);
                    break; // Break if no exception, otherwise retry
                }
                catch (Exception)
                {
                    // If there was an exception last try, propragate exception
                    if (i == retryCount - 1)
                        throw;
                }
            }
        }
Beispiel #4
0
 private async Task ExecuteServerListener(CancellationToken cancellationToken)
 {
     using (var listener = new TcpSocketListener(0))
     {
         listener.ConnectionReceived = ConnectionReceived;
         await listener.StartListeningAsync(Port);
         try
         {
             for (; ;)
             {
                 cancellationToken.ThrowIfCancellationRequested();
                 await Task.Delay(100, cancellationToken);
             }
         }
         finally
         {
             await listener.StopListeningAsync();
             foreach (var connection in _connections.ToArray())
                 connection.Close();
         }
     }
 }
Beispiel #5
0
        /// <inheritdoc/>
        public override async Task<FtpResponse> Process(FtpCommand command, CancellationToken cancellationToken)
        {
            if (Data.PassiveSocketClient != null)
            {
                await Data.PassiveSocketClient.DisconnectAsync();
                Data.PassiveSocketClient.Dispose();
                Data.PassiveSocketClient = null;
            }

            if (Data.TransferTypeCommandUsed != null && !string.Equals(command.Name, Data.TransferTypeCommandUsed, StringComparison.OrdinalIgnoreCase))
                return new FtpResponse(500, $"Cannot use {command.Name} when {Data.TransferTypeCommandUsed} was used before.");

            int port;
            var isEpsv = string.Equals(command.Name, "EPSV", StringComparison.OrdinalIgnoreCase);
            if (isEpsv)
            {
                if (string.IsNullOrEmpty(command.Argument) || string.Equals(command.Argument, "ALL", StringComparison.OrdinalIgnoreCase))
                {
                    port = 0;
                }
                else
                {
                    port = Convert.ToInt32(command.Argument, 10);
                }
            }
            else
            {
                port = 0;
            }

            Data.TransferTypeCommandUsed = command.Name;

            var sem = new SemaphoreSlim(0, 1);
            var listener = new TcpSocketListener();
            listener.ConnectionReceived += (sender, args) =>
            {
                Data.PassiveSocketClient = args.SocketClient;
                sem.Release();
            };
            await listener.StartListeningAsync(port);
            if (isEpsv || Server.ServerAddress.Contains(":"))
            {
                var listenerAddress = new Address(listener.LocalPort);
                await Connection.WriteAsync(new FtpResponse(229, $"Entering Passive Mode ({listenerAddress})."), cancellationToken);
            }
            else
            {
                var listenerAddress = new Address(Server.ServerAddress, listener.LocalPort);
                await Connection.WriteAsync(new FtpResponse(227, $"Entering Passive Mode ({listenerAddress})."), cancellationToken);
            }
            await sem.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
            await listener.StopListeningAsync();
            listener.Dispose();

            return null;
        }
        public async Task TcpSocketClient_ShouldSendReceiveData()
        {
            var bytesToSend = new byte[] {0x1, 0x2, 0x3, 0x4, 0x5};
            var len = bytesToSend.Length;
            var port = PortGranter.GrantPort();

            var listener = new TcpSocketListener();
            await listener.StartListeningAsync(port);

            var tcs = new TaskCompletionSource<bool>();
            listener.ConnectionReceived += async (sender, args) =>
            {
                var bytesReceived = new byte[len];
                await args.SocketClient.ReadStream.ReadAsync(bytesReceived, 0, len);

                var allSame =
                    Enumerable
                        .Zip(bytesToSend,
                            bytesReceived,
                            (s, r) => s == r)
                        .All(b => b);

                tcs.SetResult(allSame);
            };

            var client = new TcpSocketClient();
            await client.ConnectAsync("127.0.0.1", port);
            await client.WriteStream.WriteAsync(bytesToSend, 0, len);

            var ok = await tcs.Task;

            await listener.StopListeningAsync();

            Assert.True(ok);
        }
        [InlineData(1000)] // yes buffered stream
        public async Task TcpSocketClient_ShouldBeAbleToDisconnectThenReconnect(int bufferSize)
        {
            TcpSocketClient sut = null;

            var port = PortGranter.GrantPort();
            var listener = new TcpSocketListener();
            await listener.StartListeningAsync(port);

            if (bufferSize != -1)
                sut = new TcpSocketClient(bufferSize);
            else
                sut = new TcpSocketClient();

            await sut.ConnectAsync("127.0.0.1", port);
            await sut.DisconnectAsync();

            await sut.ConnectAsync("127.0.0.1", port); 
            await sut.DisconnectAsync();

            await listener.StopListeningAsync();
        }
        private Task ExecuteServerListener(AutoResetEvent e)
        {
            return Task.Run(() =>
            {
                _log = LogManager?.CreateLog(typeof(FtpServer));
                using (var listener = new TcpSocketListener(0))
                {
                    listener.ConnectionReceived = ConnectionReceived;
                    try
                    {
                        e.Reset();
                        listener.StartListeningAsync(Port).Wait();
                        _log?.Debug("Server listening on port {0}", Port);

                        try
                        {
                            e.WaitOne();
                        }
                        finally
                        {
                            listener.StopListeningAsync().Wait();
                            foreach (var connection in _connections.ToArray())
                                connection.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        _log?.Fatal(ex, "{0}", ex.Message);
                    }
                }
            }
            );
        }