AcceptTcpClient Method

TcpListener.AcceptTcpClient Method

Accepts a pending connection request

Namespace: System.Net.Sockets
Assembly: System (in system.dll)

public TcpClient AcceptTcpClient ()
public TcpClient AcceptTcpClient ()
public function AcceptTcpClient () : TcpClient

Return Value

A TcpClient used to send and receive data.

Exception typeCondition

InvalidOperationException

The listener has not been started with a call to Start.

SocketException

Use the SocketException.ErrorCode property to obtain the specific error code. When you have obtained this code, you can refer to the Windows Sockets version 2 API error code documentation in MSDN for a detailed description of the error.

AcceptTcpClient is a blocking method that returns a TcpClient that you can use to send and receive data. Use the Pending method to determine if connection requests are available in the incoming connection queue if you want to avoid blocking.

Use the TcpClient.GetStream method to obtain the underlying NetworkStream of the returned TcpClient. The NetworkStream will provide you with methods for sending and receiving with the remote host. When you are through with the TcpClient, be sure to call its Close method. If you want greater flexibility than a TcpClient offers, consider using AcceptSocket.

NoteNote

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing.

In the following code example, the AcceptTcpClient method is used to return a TcpClient. This TcpClient is used to communicate with the newly connected client.


     // Create a socket and connect with a remote host.
IPHostEntry myIpHostEntry = Dns.Resolve("www.contoso.com");
IPEndPoint myIpEndPoint = new IPEndPoint(myIpHostEntry.AddressList[0], 1001);

     Socket mySocket = new Socket(myIpEndPoint.Address.AddressFamily,
                                SocketType.Stream,
                                       ProtocolType.Tcp);
     try{
          mySocket.Connect(myIpEndPoint);
     
          
          // Create the NetworkStream for communicating with the remote host.
          NetworkStream myNetworkStream;
          
          if (networkStreamOwnsSocket){
               myNetworkStream = new NetworkStream(mySocket, true);          
          }
          else{
               myNetworkStream = new NetworkStream(mySocket);     
          }

         
          // Check to see if this NetworkStream is writable.
          if (myNetworkStream.CanWrite){
             
               byte[] myWriteBuffer = Encoding.ASCII.GetBytes("Are you receiving this message?");
               myNetworkStream.Write(myWriteBuffer, 0, myWriteBuffer.Length);
          }
          else{
               Console.WriteLine("Sorry.  You cannot write to this NetworkStream.");  
          }


         
          // Check to see if this NetworkStream is readable.
          if(myNetworkStream.CanRead){
              byte[] myReadBuffer = new byte[1024];
              StringBuilder myCompleteMessage = new StringBuilder();
              int numberOfBytesRead = 0;

              // Incoming message may be larger than the buffer size.
              do{
                   numberOfBytesRead = myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);

                   myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
                                   
              }
              while(myNetworkStream.DataAvailable);

              // Print out the received message to the console.
              Console.WriteLine("You received the following message : " +
                                           myCompleteMessage);
          }
          else{
               Console.WriteLine("Sorry.  You cannot read from this NetworkStream.");
          }



          // Close the NetworkStream
          myNetworkStream.Close();

     }
     catch (Exception exception){
          Console.WriteLine("Exception Thrown: " + exception.ToString());
     }
     

  }


/**
* The following function creates a TcpServer that connects to  
* the specified port (13000).Any TcpClient that wants to use this server
* has to explicitly connect to an address obtained by the combination of
* the sever on which this TCpServer is runnig and the port 13000. 
* This TcpServer simply echoes back the message sent by the TcpClient, 
* after translating it into uppercase. 
* Refer to the related client in the TcpClient class. 
*/
public static void main(String[] args)
{
    try {
        // Set the TcpListener on port 13000.
        int port = 13000;
        TcpListener server = new TcpListener(port);

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

        // Buffer for reading data
        ubyte bytes[] = new ubyte[256];
        String data = null;

        // Enter the listening loop.
        while (true) {
            Console.Write("Waiting for a connection... ");

            // Perform a blocking call to accept requests.
            // You could also user server.AcceptSocket() here.
            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("Connected!");
            data = null;

            // Get a stream object for reading and writing
            NetworkStream stream = client.GetStream();
            int i;

            // Loop to receive all the data sent by the client.
            while (((i = stream.Read(bytes, 0, bytes.length)) != 0)) {
                // Translate data bytes to a ASCII string.
                data = System.Text.Encoding.get_ASCII().GetString(
                    bytes, 0, i);
                Console.WriteLine(String.Format("Received: {0}", data));

                // Process the data sent by the client.
                data = data.ToUpper();
                ubyte msg[] = System.Text.Encoding.get_ASCII().GetBytes(
                    data);

                // Send back a response.
                stream.Write(msg, 0, msg.length);
                Console.WriteLine(String.Format("Sent: {0}", data));
            }

            // Shutdown and end connection
            client.Close();
        }
    }
    catch (SocketException e) {
        Console.WriteLine("SocketException: {0}", e);
    }
    Console.WriteLine("\nHit enter to continue...");
    Console.Read();
} //main

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show:
© 2016 Microsoft