当前位置: 首页>>代码示例>>C#>>正文


C# TcpListener.AcceptSocketAsync方法代码示例

本文整理汇总了C#中System.Net.Sockets.TcpListener.AcceptSocketAsync方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.AcceptSocketAsync方法的具体用法?C# TcpListener.AcceptSocketAsync怎么用?C# TcpListener.AcceptSocketAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.TcpListener的用法示例。


在下文中一共展示了TcpListener.AcceptSocketAsync方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AcceptMany

        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);
        }
开发者ID:cilliemalan,项目名称:Mqtt,代码行数:31,代码来源:Program.cs

示例2: RespondToOneMsg

 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);
     }
 }
开发者ID:kapilash,项目名称:dc,代码行数:17,代码来源:Program.cs

示例3: TcpSocket_maps_to_MessageFrameQueueWriter

        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);
            }
        }
开发者ID:tleviathan,项目名称:redfoxmq,代码行数:19,代码来源:MessageFrameWriterFactoryTests.cs

示例4: TcpListenerProcess

        /// <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.");
            }
        }
开发者ID:jonathanyeung,项目名称:ozwego,代码行数:43,代码来源:TCPListener.cs

示例5: Thread

        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();
        }
开发者ID:buddyfavors,项目名称:CoCSharp,代码行数:22,代码来源:JsonSocketProxyService.cs

示例6: Start

		public void Start ()
		{
			if (IsListening)
				return;
			if (!(Environment.GetEnvironmentVariable ("MONO_DEBUG")?.Contains ("disable_omit_fp") ?? false)) {
				MessageService.ShowWarning ("Set environment variable",
											[email protected]"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 ();
		}
开发者ID:sushihangover,项目名称:monodevelop,代码行数:39,代码来源:UIThreadMonitor.cs

示例7: ListenerAsync

 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);
     }
 }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:24,代码来源:QuoteServer.cs

示例8: InterceptAsync

        /// <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;
        }
开发者ID:habb0,项目名称:Sulakore,代码行数:15,代码来源:HNode.cs

示例9: ListenAsync

        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(); }
        }
开发者ID:SirJamal,项目名称:Sulakore,代码行数:13,代码来源:HNode.cs

示例10: StartAsync

        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();
            }
        }
开发者ID:ESgarbi,项目名称:corefx,代码行数:98,代码来源:LoopbackGetRequestHttpProxy.cs

示例11: AcceptSocketAsync

        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);
        }
开发者ID:ViPetroFF,项目名称:zcahttpproxy,代码行数:35,代码来源:CAHTTPProxy.cs

示例12: StartServer

        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;
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:74,代码来源:LoopbackServer.cs

示例13: ListenAsync

        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");
            }
        }
开发者ID:bestpetrovich,项目名称:devicehive-.net,代码行数:29,代码来源:TcpSocketMessageBus.cs

示例14: ListenThread

		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();
			}
		}
开发者ID:abstractmachine,项目名称:Fungus-3D-Template,代码行数:53,代码来源:MoonSharpVsCodeDebugServer.cs


注:本文中的System.Net.Sockets.TcpListener.AcceptSocketAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。