AcceptSocketAsync() public méthode

public AcceptSocketAsync ( ) : Task
Résultat Task
Exemple #1
0
        private static async Task AcceptMany(TcpListener tcpListener, int howMany)
        {
            List<WeakReference<Task>> waitingFor = new List<WeakReference<Task>>();
            for (int i = 1; howMany == 0 || i <= howMany; i++)
            {
                Console.WriteLine("Waiting for {0}", i);
                Stopwatch sw = new Stopwatch(); sw.Start();
                var listener = await tcpListener.AcceptSocketAsync();
                sw.Stop();
                Console.WriteLine("Accepted {0} in {1} milliseconds", i, sw.ElapsedMilliseconds);

                //var workTask = WorkWith(i, listener);

                //if (!workTask.IsCompleted) waitingFor.Add(new WeakReference<Task>(workTask));
            }

            Console.WriteLine("Maximum requests processed. Waiting for them to finish");

            var toWaitFor = waitingFor.Select(x =>
            {
                Task tsk;
                if (!x.TryGetTarget(out tsk))
                {
                    Console.WriteLine("Failed to get task");
                }

                return tsk;
            }).Where(x => x != null && !x.IsCompleted);

            await Task.WhenAll(toWaitFor);
        }
Exemple #2
0
        protected async Task <Stream> AcceptStreamAsync(System.Net.Sockets.TcpListener listener)
        {
            try
            {
                LoggerHelper.Debug($"Accept stream on {listener.LocalEndpoint.ToString()}");
                Socket = await listener.AcceptSocketAsync();

                BaseStream   = new NetworkStream(Socket);
                LastActivity = DateTime.Now;

                if (IsDataConnection)
                {
                    if (Configuration.ShouldEncrypt && Configuration.EncryptionType == FtpEncryption.Explicit)
                    {
                        await ActivateEncryptionServerAsync();
                    }
                }
                else
                {
                    if (Configuration.ShouldEncrypt && Configuration.EncryptionType == FtpEncryption.Implicit)
                    {
                        await ActivateEncryptionServerAsync();
                    }
                }
                return(this);
            }
            catch (Exception exception)
            {
                LoggerHelper.Error($"Could accept connect {listener.LocalEndpoint.ToString()} :{exception.ToString()}");
                throw;
            }
        }
Exemple #3
0
        private async Task AcceptAsync(CancellationToken t)
        {
            Log.Information("{0}.{1}: Accepting connections...", this, nameof(AcceptAsync));
            while (!t.IsCancellationRequested)
            {
                Socket socket = null;

                try
                {
                    socket = await listener.AcceptSocketAsync();

                    var connection = EpoxyConnection.MakeServerConnection(
                        parentTransport,
                        this,
                        serviceHost,
                        socket);
                    socket = null; // connection now owns the socket and will close it

                    lock (connectionsLock)
                    {
                        connections.Add(connection);
                    }

                    await connection.StartAsync();

                    Log.Debug("{0}.{1}: Accepted connection from {2}.",
                              this, nameof(AcceptAsync), connection.RemoteEndPoint);
                }
                catch (SocketException ex)
                {
                    Log.Fatal(ex, "{0}.{1}: Accept failed with error {2}.",
                              this, nameof(AcceptAsync), ex.SocketErrorCode);

                    ShutdownSocketSafe(socket);
                }
                catch (ObjectDisposedException)
                {
                    ShutdownSocketSafe(socket);

                    // TODO: ignoring this exception is needed during shutdown,
                    //       but there should be a cleaner way. We should
                    //       switch to having a proper life-cycle for a
                    //       connection.
                }
            }
            Log.Information("{0}.{1}: Shutting down.", this, nameof(AcceptAsync));
        }
Exemple #4
0
        private async Task AcceptAsync(CancellationToken t)
        {
            logger.Site().Information("Accepting connections on {0}", ListenEndpoint);
            while (!t.IsCancellationRequested)
            {
                Socket socket = null;

                try
                {
                    socket = await listener.AcceptSocketAsync();

                    var connection = EpoxyConnection.MakeServerConnection(
                        parentTransport,
                        this,
                        serviceHost,
                        socket,
                        logger,
                        metrics);
                    socket = null; // connection now owns the socket and will close it

                    lock (connectionsLock)
                    {
                        connections.Add(connection);
                    }

                    await connection.StartAsync();

                    logger.Site().Debug("Accepted connection from {0}.", connection.RemoteEndPoint);
                }
                catch (SocketException ex)
                {
                    logger.Site().Error(ex, "Accept failed with error {0}.", ex.SocketErrorCode);

                    ShutdownSocketSafe(socket, logger);
                }
                catch (ObjectDisposedException)
                {
                    ShutdownSocketSafe(socket, logger);

                    // TODO: ignoring this exception is needed during shutdown,
                    //       but there should be a cleaner way. We should
                    //       switch to having a proper life-cycle for a
                    //       connection.
                }
            }
            logger.Site().Information("Shutting down connection on {0}", ListenEndpoint);
        }
Exemple #5
0
 private static async Task RespondToOneMsg(TcpListener listener)
 {
     var socket = await listener.AcceptSocketAsync();
     var client = await listener.AcceptTcpClientAsync();
     Console.WriteLine("Connected");
     using (var stream = new NegotiateStream(client.GetStream()))
     {
         await stream.AuthenticateAsServerAsync(CredentialCache.DefaultNetworkCredentials, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
         Console.WriteLine($"remote {stream.RemoteIdentity.AuthenticationType}");
         Console.WriteLine($"remote name = {stream.RemoteIdentity.Name}");
         var recvBuffer = new byte[1024];
         var byteCount = stream.Read(recvBuffer, 0, recvBuffer.Length);
         Console.WriteLine(Encoding.UTF8.GetString(recvBuffer, 0, byteCount));
         var sendBuffer = Encoding.UTF8.GetBytes("Reply from server");
         stream.Write(sendBuffer, 0, sendBuffer.Length);
     }
 }
        public void TcpSocket_maps_to_MessageFrameQueueWriter()
        {
            var port = TestHelpers.GetFreePort();
            
            var server = new TcpListener(IPAddress.Loopback, port);
            server.Start();
            server.AcceptSocketAsync();
            
            using (var client = new TcpClient())
            {
                client.Connect(IPAddress.Loopback, port);
                var socket = new TcpSocket(new RedFoxEndpoint(), client);

                var factory = new MessageFrameWriterFactory();
                var writer = factory.CreateWriterFromSocket(socket);

                Assert.IsInstanceOf<MessageFrameStreamWriter>(writer);
            }
        }
Exemple #7
0
        /// <summary>
        /// TCP thread that listens for incoming connections.
        /// </summary>
        public static async void TcpListenerProcess()
        {
            Trace.WriteLine("TCP: Starting TcpListener...");

            //IPAddress addr = IPAddress.Loopback;

            try
            {


#if DEBUG
                const int port = 4032;
                var addr = new IPAddress(new byte[] { 192, 168, 1, 2 });
                var listener = new TcpListener(addr, port);
                Trace.WriteLine(string.Format("TCP: Listening on {0}:{1}...", addr, port));
#else
                var listener = new TcpListener(
                    RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint1"].IPEndpoint);

                listener.ExclusiveAddressUse = false;
#endif

                listener.Start();

                while (true)
                {
                    var socket = await listener.AcceptSocketAsync();
                    var newClient = new Client(socket);
                    newClient.OnDisconnected += OnClientDisconnected;

                    //WorkerRole.ClientManager.GlobalClientList.Add(newClient);
                    newClient.ReceiveAsync();
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(string.Format("TCP: Caught exception!! '{0}'\n{1}", e.Message, e.StackTrace));
                Trace.WriteLine("TcpListener shutting down.");
            }
        }
        void IProxyService.Start()
        {
            ProxyClients = new ConcurrentDictionary<IntPtr, Socket>();
            new Thread(async t =>
            {
                ProxyConnection = new TcpListener(IPAddress.Any, 3939);
                ProxyConnection.Start();

                while (true)
                {
                    var socket = await ProxyConnection.AcceptSocketAsync();
                    ProxyClients.Clear();
                    ProxyClients.TryAdd(socket.Handle, socket);

                    var socketAsyncEventArgs = new SocketAsyncEventArgs();
                    byte[] buffer = new byte[8192];
                    socketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length);
                    socketAsyncEventArgs.Completed += SocketAsyncEventArgs_Completed;
                    socket.ReceiveAsync(socketAsyncEventArgs);
                }
            }).Start();
        }
		public void Start ()
		{
			if (IsListening)
				return;
			if (!(Environment.GetEnvironmentVariable ("MONO_DEBUG")?.Contains ("disable_omit_fp") ?? false)) {
				MessageService.ShowWarning ("Set environment variable",
											$@"It is highly recommended to set environment variable ""MONO_DEBUG"" to ""disable_omit_fp"" and restart {BrandingService.ApplicationName} to have better results.");
			}
			IsListening = true;
			//start listening on random port
			listener = new TcpListener (IPAddress.Loopback, 0);
			listener.Start ();
			listener.AcceptSocketAsync ().ContinueWith (t => {
				if (!t.IsFaulted && !t.IsCanceled) {
					socket = t.Result;
					tcpLoopThread = new Thread (new ThreadStart (TcpLoop));
					tcpLoopThread.IsBackground = true;
					tcpLoopThread.Start ();
					listener.Stop ();
				}
			});
			//get random port provided by OS
			var port = ((IPEndPoint)listener.LocalEndpoint).Port;
			process = new Process ();
			process.StartInfo.FileName = "mono";
			process.StartInfo.Arguments = $"{typeof (UIThreadMonitorDaemon.MainClass).Assembly.Location} {port} {Process.GetCurrentProcess ().Id}";
			process.StartInfo.UseShellExecute = false;
			process.StartInfo.RedirectStandardOutput = true;
			process.StartInfo.RedirectStandardError = true;//Ignore it, otherwise it goes to IDE logging
			process.Start ();
			process.StandardError.ReadLine ();
			dumpsReaderThread = new Thread (new ThreadStart (DumpsReader));
			dumpsReaderThread.IsBackground = true;
			dumpsReaderThread.Start ();

			pumpErrorThread = new Thread (new ThreadStart (PumpErrorStream));//We need to read this...
			pumpErrorThread.IsBackground = true;
			pumpErrorThread.Start ();
		}
 protected async Task ListenerAsync()
 {
     try
     {
         IPAddress ipAddress = IPAddress.Any;
         _listener = new TcpListener(ipAddress, _port);
         _listener.Start();
         while (true)
         {
             using (Socket clientSocket = await _listener.AcceptSocketAsync())
             {
                 string message = GetRandomQuoteOfTheDay();
                 var encoder = new UnicodeEncoding();
                 byte[] buffer = encoder.GetBytes(message);
                 clientSocket.Send(buffer, buffer.Length, 0);
             }
         }
     }
     catch (SocketException ex)
     {
         Trace.TraceError($"QuoteServer {ex.Message}");
         throw new QuoteException("socket error", ex);
     }
 }
        private static async Task<ProxyResult> StartAsync(TcpListener listener, bool requireAuth, bool expectCreds)
        {
            ProxyResult result = new ProxyResult();
            var headers = new Dictionary<string, string>();
            Socket clientSocket = null;
            Stream clientStream = null;
            StreamReader clientReader = null;
            string url = null;
            try
            {
                // Get and parse the incoming request.
                Func<Task> getAndReadRequest = async () => {
                    clientSocket = await listener.AcceptSocketAsync().ConfigureAwait(false);
                    clientStream = new NetworkStream(clientSocket, ownsSocket: false);
                    clientReader = new StreamReader(clientStream, Encoding.ASCII);
                    headers.Clear();

                    url = clientReader.ReadLine().Split(' ')[1];
                    string line;
                    while (!string.IsNullOrEmpty(line = clientReader.ReadLine()))
                    {
                        string[] headerParts = line.Split(':');
                        headers.Add(headerParts[0].Trim(), headerParts[1].Trim());
                    }
                };
                await getAndReadRequest().ConfigureAwait(false);

                // If we're expecting credentials, look for them, and if we didn't get them, send back 
                // a 407 response. Optionally, process a new request that would expect credentials.
                if (requireAuth && !headers.ContainsKey("Proxy-Authorization"))
                {
                    // Send back a 407
                    await clientSocket.SendAsync(
                        new ArraySegment<byte>(Encoding.ASCII.GetBytes("HTTP/1.1 407 Proxy Auth Required\r\nProxy-Authenticate: Basic\r\n\r\n")),
                        SocketFlags.None).ConfigureAwait(false);
                    clientSocket.Shutdown(SocketShutdown.Send);
                    clientSocket.Dispose();

                    if (expectCreds)
                    {
                        // Wait for a new connection that should have an auth header this time and parse it.
                        await getAndReadRequest().ConfigureAwait(false);
                    }
                    else
                    {
                        // No credentials will be coming in a subsequent request.
                        return default(ProxyResult);
                    }
                }

                // Store any auth header we may have for later comparison.
                string authValue;
                if (headers.TryGetValue("Proxy-Authorization", out authValue))
                {
                    result.AuthenticationHeaderValue = Encoding.UTF8.GetString(Convert.FromBase64String(authValue.Substring("Basic ".Length)));
                }

                // Forward the request to the server.
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                foreach (var header in headers) request.Headers.Add(header.Key, header.Value);
                using (HttpClient outboundClient = new HttpClient())
                using (HttpResponseMessage response = await outboundClient.SendAsync(request).ConfigureAwait(false))
                {
                    // Transfer the response headers from the server to the client.
                    var sb = new StringBuilder($"HTTP/{response.Version.ToString(2)} {(int)response.StatusCode} {response.ReasonPhrase}\r\n");
                    foreach (var header in response.Headers.Concat(response.Content.Headers))
                    {
                        sb.Append($"{header.Key}: {string.Join(", ", header.Value)}\r\n");
                    }
                    sb.Append("\r\n");
                    byte[] headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
                    await clientStream.WriteAsync(headerBytes, 0, headerBytes.Length).ConfigureAwait(false);

                    // Forward the content from the server, both to the client and to a memory stream which we'll use
                    // to return the data from the proxy.
                    var resultBody = new MemoryStream();
                    using (Stream responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                    {
                        byte[] buffer = new byte[0x1000];
                        int bytesRead = 0;
                        while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            await clientStream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
                            resultBody.Write(buffer, 0, bytesRead);
                        }
                    }

                    // Return the result
                    result.ResponseContent = resultBody.ToArray();
                    return result;
                }
            }
            finally
            {
                clientSocket.Dispose();
                listener.Stop();
            }
        }
Exemple #12
0
        public async Task <ITransport> AcceptConnection()
        {
            var socket = await _listener.AcceptSocketAsync();

            return(new SocketTransport(socket, _socketSettings, _loggerFactory));
        }
Exemple #13
0
        /// <summary>
        /// Returns a <see cref="HNode"/> that was intercepted on the specified port in an asynchronous operation.
        /// </summary>
        /// <param name="port">The port to listen to for local connection attempts.</param>
        /// <returns></returns>
        public static async Task<HNode> InterceptAsync(int port)
        {
            var listener = new TcpListener(IPAddress.Loopback, port);
            listener.Start();

            var node = new HNode(await listener.AcceptSocketAsync());
            listener.Stop();

            return node;
        }
        private async Task ListenAsync()
        {
            var listener = new TcpListener(IPAddress.Any, _configuration.ServerPort);
            listener.Start();
            _log.InfoFormat("TCP listener started on port {0}", _configuration.ServerPort);

            try
            {
                while (true)
                {
                    var acceptTask = listener.AcceptSocketAsync();
                    if (await Task.WhenAny(acceptTask, _cancelTaskCompletionSource.Task) != acceptTask)
                        return;

                    var socket = acceptTask.Result;
                    _log.InfoFormat("Accepted connection from: {0}", socket.RemoteEndPoint);
                    var task = Task.Run(async () => await ReceiveAsync(socket));
                }
            }
            catch (Exception ex)
            {
                _log.Error("Error while listening for TCP clients", ex);
            }
            finally
            {
                listener.Stop();
                _log.Info("TCP listener stopped");
            }
        }
Exemple #15
0
        public static async Task<HNode> ListenAsync(int port)
        {
            var listener = new TcpListener(IPAddress.Any, port);
            try
            {
                listener.Start();
                Socket client = await listener.AcceptSocketAsync()
                    .ConfigureAwait(false);

                return new HNode(client);
            }
            finally { listener.Stop(); }
        }
Exemple #16
0
 //
 // Summary:
 //     Begins an asynchronous operation to accept an incoming connection attempt.
 //
 // Parameters:
 //   callback:
 //     An System.AsyncCallback delegate that references the method to invoke when the
 //     operation is complete.
 //
 //   state:
 //     A user-defined object containing information about the accept operation. This
 //     object is passed to the callback delegate when the operation is complete.
 //
 // Returns:
 //     An System.IAsyncResult that references the asynchronous creation of the System.Net.Sockets.Socket.
 //
 // Exceptions:
 //   T:System.Net.Sockets.SocketException:
 //     An error occurred while attempting to access the socket. See the Remarks section
 //     for more information.
 //
 //   T:System.ObjectDisposedException:
 //     The System.Net.Sockets.Socket has been closed.
 public static IAsyncResult BeginAcceptSocket(this TcpListener listener, AsyncCallback callback, object state)
 {
     return(TaskToApm.Begin(listener.AcceptSocketAsync(), callback, state));
 }
Exemple #17
0
        public static Task StartServer(
            TransferType transferType,
            TransferError transferError,
            out IPEndPoint serverEndPoint)
        {
            var server = new TcpListener(IPAddress.Loopback, 0);
            Task serverTask = ((Func<Task>)async delegate {
                server.Start();
                using (var client = await server.AcceptSocketAsync())
                using (var stream = new NetworkStream(client))
                using (var reader = new StreamReader(stream, Encoding.ASCII))
                {
                    // Read past request headers.
                    string line;
                    while (!string.IsNullOrEmpty(line = reader.ReadLine())) ;

                    // Determine response transfer headers.
                    string transferHeader = null;
                    string content = "This is some response content.";
                    if (transferType == TransferType.ContentLength)
                    {
                        if (transferError == TransferError.ContentLengthTooLarge)
                        {
                            transferHeader = $"Content-Length: {content.Length + 42}\r\n";
                        }
                        else
                        {
                            transferHeader = $"Content-Length: {content.Length}\r\n";
                        }
                    }
                    else if (transferType == TransferType.Chunked)
                    {
                        transferHeader = "Transfer-Encoding: chunked\r\n";
                    }

                    // Write response.
                    using (var writer = new StreamWriter(stream, Encoding.ASCII))
                    {
                        writer.Write("HTTP/1.1 200 OK\r\n");
                        writer.Write($"Date: {DateTimeOffset.UtcNow:R}\r\n");
                        writer.Write("Content-Type: text/plain\r\n");

                        if (!string.IsNullOrEmpty(transferHeader))
                        {
                            writer.Write(transferHeader);
                        }

                        writer.Write("\r\n");
                        if (transferType == TransferType.Chunked)
                        {
                            string chunkSizeInHex = string.Format(
                                "{0:x}\r\n",
                                content.Length + (transferError == TransferError.ChunkSizeTooLarge ? 42 : 0));
                            writer.Write(chunkSizeInHex);
                            writer.Write($"{content}\r\n");
                            if (transferError != TransferError.MissingChunkTerminator)
                            {
                                writer.Write("0\r\n\r\n");
                            }
                        }
                        else
                        {
                            writer.Write($"{content}\r\n");
                        }
                        writer.Flush();
                    }

                    client.Shutdown(SocketShutdown.Both);
                }
            })();

            serverEndPoint = (IPEndPoint)server.LocalEndpoint;
            return serverTask;
        }
Exemple #18
0
        public async Task <ISocket> AcceptSocket()
        {
            var socket = await _listener.AcceptSocketAsync();

            return(new TcpSocket(socket, _socketSettings, _loggerFactory));
        }
		private void ListenThread(TcpListener serverSocket)
		{
			try
			{
				while (!m_StopEvent.WaitOne(0))
				{
#if DOTNET_CORE
					var task = serverSocket.AcceptSocketAsync();
					task.Wait();
					var clientSocket = task.Result;
#else
					var clientSocket = serverSocket.AcceptSocket();
#endif

					if (clientSocket != null)
					{
						string sessionId = Guid.NewGuid().ToString("N");
						Log("[{0}] : Accepted connection from client {1}", sessionId, clientSocket.RemoteEndPoint);

						SpawnThread("VsCodeDebugSession_" + sessionId, () =>
						{
							using (var networkStream = new NetworkStream(clientSocket))
							{
								try
								{
									RunSession(sessionId, networkStream);
								}
								catch (Exception ex)
								{
									Log("[{0}] : Error : {1}", ex.Message);
								}
							}

#if DOTNET_CORE
							clientSocket.Dispose();
#else
							clientSocket.Close();
#endif
							Log("[{0}] : Client connection closed", sessionId);
						});
					}
				}
			}
			catch (Exception e)
			{
				Log("Fatal error in listening thread : {0}", e.Message);
			}
			finally
			{
				if (serverSocket != null)
					serverSocket.Stop();
			}
		}
Exemple #20
0
        private async void AcceptSocketAsync(TcpListener listener)
        {
            bool bRepeat = true;

            do
            {
                try
                {
                    // End the operation and display the received data on 
                    // the console.
                    Socket client = await listener.AcceptSocketAsync();

                    // Process the connection here. (Add the client to a
                    // server table, read data, etc.)
                    //Console.WriteLine("Client connected completed");

                    new CAHttpClient(this, client, listener);
                    //new HttpClient(this, client, listener);
                    bRepeat = false;
                }
                catch (SocketException excep)
                {
                    Console.WriteLine("Accept tcp connection failed, error:");
                    Console.WriteLine(excep.Message);
                    //listener.BeginAcceptSocket(OnAcceptNewClient, listener);
                }
                catch (Exception excep)
                {
                    Console.WriteLine("Exception listener.AcceptSocketAsync()");
                    Console.WriteLine(excep.Message);
                    bRepeat = false;
                }
            }
            while (bRepeat);
        }