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


C# TcpListener.EndAcceptTcpClient方法代码示例

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


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

示例1: Main

    public static void Main()
    {
        TcpListener server = new TcpListener(IPAddress.Any, 8888);
        server.Start();

        Console.WriteLine(":: EchoServer running ::");

		AsyncCallback callback = null;
		server.BeginAcceptTcpClient(callback = ((ares) => {
			TcpClient session = server.EndAcceptTcpClient(ares);
			int sessionId = ++SessionCount;

			server.BeginAcceptTcpClient(callback, null);
			
			StartAttend(sessionId, session);
			
		}), null);
		
		Console.ReadLine();
    }
开发者ID:Skyish,项目名称:isel-pc-1516-1,代码行数:20,代码来源:EchoServer_Asynch.cs

示例2: MultiThreadedServer

    //
    // The multithreaded TCP server.
    //
    public static void MultiThreadedServer()
    {
        TcpListener server = null;
        try	{

            //
            // Create a listen socket bound to the server port.
            //

            server = new TcpListener(IPAddress.Loopback, SERVER_PORT);

            //
            // Start the first AcceptTcpClient
            //

            AsyncCallback OnAccept = null;

            OnAccept = delegate (IAsyncResult ar) {
                TcpClient client = null;
                try {

                    //
                    // Get the socket that will be used to communicate with the connected client.
                    //

                    client = server.EndAcceptTcpClient(ar);
                } catch (ObjectDisposedException) {

                    //
                    // Accept callback was called because the server socket was closed, so return.
                    //

                    return;
                }

                //
                // The server is ready to accepts a new connection.
                //

                server.BeginAcceptTcpClient(OnAccept, null);

                //
                // Process the current connection.
                //

                ProcessConnection(client);
            };

            //
            // Start listening for client requests.
            //

            server.Start();
            server.BeginAcceptTcpClient(OnAccept, null);

            //
            // This thread is free to do anything we need.
            //

            Console.WriteLine("Hit enter to terminate the server...");
            Console.ReadLine();

            //
            // Close the listener socket.
            //

            server.Stop();
        } catch(SocketException e) {
            Console.WriteLine("SocketException: {0}", e);
        }
    }
开发者ID:prompt,项目名称:preprompt-parallel,代码行数:74,代码来源:tcpsvr.cs

示例3: Process

        private static IEnumerator<Int32> Process(AsyncEnumerator ae, TcpListener server)
        {
            server.BeginAcceptTcpClient(ae.End(), null);
             yield return 1;

             using (TcpClient client = server.EndAcceptTcpClient(ae.DequeueAsyncResult())) {

            Start(server);  // Accept another client

            using (Stream stream = client.GetStream()) {
               // Read 1 byte from client which contains length of additional data
               Byte[] inputData = new Byte[1];
               stream.BeginRead(inputData, 0, 1, ae.End(), null);
               yield return 1;

               // Client closed connection; abandon this client request
               if (stream.EndRead(ae.DequeueAsyncResult()) == 0) yield break;

               // Start to read 'length' bytes of data from client
               Int32 dataLength = inputData[0];
               Array.Resize(ref inputData, 1 + dataLength);

               for (Byte bytesReadSoFar = 0; bytesReadSoFar < dataLength; ) {
                  stream.BeginRead(inputData, 1 + bytesReadSoFar,
                     inputData.Length - (bytesReadSoFar + 1), ae.End(), null);
                  yield return 1;

                  // Get number of bytes read from client
                  Int32 numBytesReadThisTime = stream.EndRead(ae.DequeueAsyncResult());
                  // Client closed connection; abandon this client request
                  if (numBytesReadThisTime == 0) yield break;

                  // Continue to read bytes from client until all bytes are in
                  bytesReadSoFar += (Byte)numBytesReadThisTime;
               }

               // All bytes have been read, process the input data
               Byte[] outputData = ProcessData(inputData);
               inputData = null;  // Allow early GC

               // Write outputData back to client
               stream.BeginWrite(outputData, 0, outputData.Length, ae.End(), null);
               yield return 1;

               stream.EndWrite(ae.DequeueAsyncResult());
            }
             }
        }
开发者ID:pdckxd,项目名称:bugtrackingsystem,代码行数:48,代码来源:TcpServer.cs

示例4: Run

    /// <summary>
    ///	Server's main loop implementation.
    /// </summary>
    /// <param name="log"> The Logger instance to be used.</param>
    public void Run(Logger log)
    {
        try{
            try
            {
                _server = new TcpListener(IPAddress.Loopback, portNumber);
                _server.Start();
            }
            catch (ArgumentOutOfRangeException argex)
            {
                MessageBox.Show(@"The port number inserted is not valid!", @"ERROR");
                _server = null;
                throw argex;
            }
            catch (SocketException sock)
            {
                MessageBox.Show(@"The specified port is already in use by another server!",
                    @"ERROR");
                _server = null;
                throw sock;
            }

            // Define the callback method - which will be called whenever a client request ends;
            AsyncCallback onAcceptCallback = null;
            int nseconds = 10;

            onAcceptCallback = delegate(IAsyncResult ar)
            {
                log.IncrementRequests();
                TcpClient socket = null;
                EndPoint clientEndPoint = null;
                try
                {
                    // Asynchronously accept an incoming connection attempt
                    // and create a new TcpClient to handle remote host communication
                    socket = _server.EndAcceptTcpClient(ar);

                    // Begin an async operation: to accept an incoming connection attempt
                    _server.BeginAcceptTcpClient(onAcceptCallback, _server);

                    // Process the accepted connection.
                    /////////////////////////////////////////////////////////////////////
                    log.LogMessage("Listener - Processing the accepted connection...");

                    socket.LingerState = new LingerOption(true, nseconds);

                    clientEndPoint = socket.Client.RemoteEndPoint;
                    log.LogMessage(String.Format("Listener - Connection established with {0}.",
                        clientEndPoint));

                    // Instantiate protocol handler and associate it to the current TCP connection
                    var protocolHandler = new Program.Handler(socket.GetStream(), log);

                    // Synchronously process request made through the connection
                    protocolHandler.Run();

                    Utils.ShowInfo(Store.Instance, log.Writer);
                    /////////////////////////////////////////////////////////////////////
                }
                catch (SocketException sockex)
                {
                    Console.WriteLine("***socket exception occurred: {0}", sockex.Message);

                }
                catch (ObjectDisposedException)
                {
                    //
                    // This exception happens when the listener socket is closed.
                    // So, we just ignore it!
                    //
                }
                log.LogMessage(socket != null && socket.Connected
                    ? String.Format("Listener - Time left for socket to be disconnected: {0} seconds.",
                        socket.Client.LingerState.LingerTime)
                    : String.Format("Listener - Connection closed with {0}.", clientEndPoint));
            };

            // Begins an asynchronous operation to accept an incoming connection attempt.
            _server.BeginAcceptTcpClient(onAcceptCallback, null);
        }

        finally
        {
            if (_server == null)
            {
                log.LogMessage("listener - ERROR: Server is undefined!");
            }

            //                    else
            //                    {
            //                        log.LogMessage("Listener - Ending.");
            //                        srv.Stop();
            //                    }
        }
    }
开发者ID:pdsrebelo,项目名称:PC_1314V_Series,代码行数:99,代码来源:Listener.cs

示例5: Main

	static void Main() {
		
		//
		// Configure the Thread Pool with a minimum of IOCP threads;
		//
		
		int worker, iocp;
		
		ThreadPool.GetMinThreads(out worker, out iocp);
		//ThreadPool.SetMinThreads(worker, MIN_IOCP_THREADS);
		
		
		//
		// Create a listen socket bind to the server port.
		//
			
		var server = new TcpListener(IPAddress.Parse("127.0.0.1"), SERVER_PORT);

		//
		// Start listening for client requests.
		//
			
		server.Start();

		//
		// Start the first AcceptTcpClient
		//
		
		AsyncCallback onAcceptProcessing = null;
		AsyncCallback onAcceptCallback = null;

		//
		// Processes an accepted connection.
		//
		
		onAcceptProcessing = delegate(IAsyncResult ar) {
			TcpClient conn = null;
			
			try {
				conn = server.EndAcceptTcpClient(ar);
        
				//
				// Increment the number of active connections and, if the we are below
				// of maximum allowed, accept a new connection.
				//

#pragma warning disable 420
				
				int c = Interlocked.Increment(ref activeConnections);
				if (!shutdownInProgress && c < MAX_ACTIVE_CONNECTIONS) {
					server.BeginAcceptTcpClient(onAcceptCallback, server);
				}
				
				//
				// Process the previously accepted connection.
				//
				
				ProcessConnection(conn);
				
				//
				// Decrement the number of active connections. If a shutdown
				// isn't in progress and if the number of active connections
				// is equals to the maximum allowed, accept a new connection.
				// Otherwise, if the number of active connections drops to
				// zero and the shutdown was initiated, set the server idle
				// event.
				//
				
				c = Interlocked.Decrement(ref activeConnections);

#pragma warning restore 420
				if (!shutdownInProgress && c == MAX_ACTIVE_CONNECTIONS - 1) {
					server.BeginAcceptTcpClient(onAcceptCallback, server);
				} else if (shutdownInProgress && c == 0) {
					serverIdle.Set();
				}
			} catch (SocketException sockex) {
				Console.WriteLine("***socket exception: {0}", sockex.Message);
			} catch (ObjectDisposedException) {
				//
				// This exception happens when th listener socket is closed.
				// So, we just ignore it!
				//
			}
		};
		
		//
		// First entry point for the OnAccept callback.
		//
		
		onAcceptCallback = delegate(IAsyncResult ar) {
		
			Console.WriteLine("-->OnAcceptCallback(#{0})", Thread.CurrentThread.ManagedThreadId);
		
			//
			// Register the current IOCP thread.
			//
			
			RegisterIocpThread();
			
//.........这里部分代码省略.........
开发者ID:Baptista,项目名称:PC,代码行数:101,代码来源:TcpMtEchoServer.cs


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