Type: System.Net.Sockets.TcpListener System.Net.Sockets.TcpListener ClassAssembly: System.dll Namespace: System.Net.Sockets Summary Listens for connections from TCP network clients. C# Syntax: public class TcpListener Remarks The TcpListener class builds upon the Socket class to provide TCP services at a higher level of abstraction. You can use a TcpListener to listen for connections from TCP clients. Application level protocols such as FTP and HTTP are built on the TcpListener class. You can create an instance of the TcpListener class by providing one of the following constructor argument lists: An IPEndPoint containing your local IP address and port number. Your IP address and port number. Just your port number. In this case, the default network interface will be used. Use the TcpListener.Start property to begin listening for incoming connection requests. Employ the TcpListener.Pending method to determine if connections are pending. Use TcpListener.AcceptSocket to retrieve a Socket, or TcpListener.AcceptTcpClient to retrieve a TcpClient used for facilitating communication with the remote machine. Finally, use TcpListener.Stop to close the underlying listening Socket. Note Calling TcpListener.Stop only closes the Socket used to listen for incoming connections. You must close any instances returned from TcpListener.AcceptSocket or TcpListener.AcceptTcpClient as well. Example The following example creates a TcpListener on port 13 that responds to an incoming connection with the current date and time, and then exits.
const int portNumber = 13;
TcpListener tcpListener = new TcpListener(portNumber);
tcpListener.Start();
Console.WriteLine("Waiting for a connection....");
try{
//Accept the pending client connection and return a TcpClient initialized for communication.
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
NetworkStream networkStream = tcpClient.GetStream();
string responseString = "You have successfully connected to me";
Byte[] sendBytes = Encoding.ASCII.GetBytes(responseString);
networkStream.Write(sendBytes, 0, sendBytes.Length);
Console.WriteLine("Message Sent /> : " + responseString);
//Any communication with the remote client using the TcpClient can go here.
//
////////
//Close TcpListener and TcpClient.
tcpClient.Close();
tcpListener.Stop();
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
See also: System.Net.Sockets Namespace | TcpClient System.Net.Sockets.TcpListener Member List: Public Constructors ctor #1 Overloaded: .ctor(int port) Initializes a new instance of the TcpListener class that listens on the specified port. ctor #2 Overloaded: .ctor(IPEndPoint localEP) Initializes a new instance of the TcpListener class with the specified local endpoint. ctor #3 Overloaded: .ctor(IPAddress localaddr, int port) Initializes a new instance of the TcpListener class that listens to the specified IP address and port. Public Properties LocalEndpoint Read-only Gets the underlying EndPoint of the current TcpListener. Public Methods AcceptSocket Accepts a pending connection request. AcceptTcpClient Accepts a pending connection request Equals (inherited from System.Object) See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. GetHashCode (inherited from System.Object) See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. GetType (inherited from System.Object) See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. Pending Determines if there are pending connection requests. Start Starts listening to network requests. Stop Closes the listener. ToString (inherited from System.Object) See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. Protected Properties Active Read-only Gets a value that indicates whether TcpListener is actively listening for client connections. Server Read-only Gets the underlying network Socket. Protected Methods Finalize Overridden: Frees resources used by the TcpClient class. MemberwiseClone (inherited from System.Object) See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. Hierarchy: System.Object System.Net.Sockets.TcpListener System.Net.Sockets.TcpListener Member DetailsOverloaded ctor #1 Summary Initializes a new instance of the TcpListener class that listens on the specified port. C# Syntax: public TcpListener( int port ); Parameters: port The port on which to listen. If this number is 0, the system will assign an open port. Exceptions Exception Type Condition ArgumentOutOfRangeException The port parameter is not between IPEndPoint.MinPort and IPEndPoint.MaxPort. Remarks The port parameter specifies the local port number on which you intend to listen. When you call TcpListener.Start, TcpListener uses the default network interface to listen for connections on the specified port. Example The following example creates an instance of the TcpListener class using a local port number.
//Creates an instance of the TcpListener class by providing a local port number.
try{
TcpListener tcpListener = new TcpListener(13);
}
catch ( Exception e ){
Console.WriteLine( e.ToString());
}
Return to top Overloaded ctor #2 Summary Initializes a new instance of the TcpListener class with the specified local endpoint. C# Syntax: public TcpListener( IPEndPoint localEP ); Parameters: localEP The local endpoint to which to bind the listener Socket. Exceptions Exception Type Condition ArgumentNullException The localEP parameter is null. Remarks The localEP parameter specifies the local IPEndPoint. This constructor creates an underlying Socket, and binds that Socket to localEp. If you call the TcpListener.Start method, TcpListener will listen for connections on localEp. Example The following example creates an instance of the TcpListener class. using the local endpoint.
//Creates an instance of the TcpListener class by providing a local endpoint.
IPAddress ipAddress = Dns.Resolve(Dns.GetHostName()).AddressList[0];
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 11000);
try{
TcpListener tcpListener = new TcpListener(ipLocalEndPoint);
}
catch ( Exception e ){
Console.WriteLine( e.ToString());
}
See also: IPEndPoint Return to top Overloaded ctor #3 Summary Initializes a new instance of the TcpListener class that listens to the specified IP address and port. C# Syntax: public TcpListener( IPAddress localaddr, int port ); Parameters: localaddr The local IP address. port The port on which to listen. Exceptions Exception Type Condition ArgumentNullException The localaddr parameter is null. ArgumentOutOfRangeException The port parameter is not between IPEndPoint.MinPort and IPEndPoint.MaxPort. Remarks TcpListener initializes its underlying IPEndPoint using the specified IP address and port number. If you call the TcpListener.Start method, TcpListener listens for connections using the underlying IPEndPoint. Example The following example creates an instance of the TcpListener class using a local IP address and port number.
//Creates an instance of the TcpListener class by providing a local IP address and port number.
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
try{
TcpListener tcpListener = new TcpListener(ipAddress, 13);
}
catch ( Exception e){
Console.WriteLine( e.ToString());
}
See also: IPAddress Return to top Property: Active (read-only) Summary Gets a value that indicates whether TcpListener is actively listening for client connections. C# Syntax: protected bool Active {get;} Remarks Classes deriving from TcpListener can use this property to keep track of the underlying Socket connection state. Note TcpClient.Active can be used to avoid redundant TcpListener.Start attempts. Return to top Property: LocalEndpoint (read-only) Summary Gets the underlying EndPoint of the current TcpListener. C# Syntax: public EndPoint LocalEndpoint {get;} Remarks You can use TcpListener.LocalEndpoint if you want to identify the local network interface and port number being used to listen for incoming client connection requests. Note To obtain address and port information, you must explicitly cast TcpListener.LocalEndpoint to return an IPEndPoint. You can then use the various methods within IPEndPoint to retrieve the desired information. See also: Socket.Listen | EndPoint Return to top Property: Server (read-only) Summary Gets the underlying network Socket. C# Syntax: protected Socket Server {get;} Remarks TcpListener creates a Socket to listen for incoming client connection requests. Classes deriving from TcpListener can use this property to get this Socket. Use the underlying Socket returned by the TcpListener.Server property if you require access beyond that which TcpListener provides. Note TcpListener.Server only returns the Socket used to listen for incoming client connection requests. Use the TcpListener.AcceptSocket method to accept a pending connection request and obtain a Socket for sending and receiving data. You can also use the TcpListener.AcceptTcpClient method to accept a pending connection request and obtain a TcpClient for sending and receiving data. See also: Socket | TcpListener.AcceptSocket | TcpListener.AcceptTcpClient Return to top Method: AcceptSocket() Summary Accepts a pending connection request. C# Syntax: public Socket AcceptSocket(); Return Value: A Socket used to send and receive data. Exceptions Exception Type Condition InvalidOperationException The listener has not been started with a call to TcpListener.Start. Remarks TcpListener.AcceptSocket returns a Socket that you can use to send and receive data. This Socket is initialized with the IP address and port number of the remote machine. You can use any of the Socket.Send and Socket.Receive methods available in the Socket class to communicate with the remote machine. Note When you finish using the Socket, be sure to call its Socket.Close method. Note If your application is relatively simple, consider using the TcpListener.AcceptTcpClient method rather than TcpListener.AcceptSocket. TcpClient provides you with simple methods for sending and receiving data over a network. Example In the following example, TcpListener.AcceptSocket is used to return a Socket. This Socket is used to communicate with the newly connected client.
// Accepts the pending client connection and returns a socket for communciation.
Socket socket = tcpListener.AcceptSocket();
Console.WriteLine("Connection accepted.");
string responseString = "You have successfully connected to me";
//Forms and sends a response string to the connected client.
Byte[] sendBytes = Encoding.ASCII.GetBytes(responseString);
int i = socket.Send(sendBytes);
Console.WriteLine("Message Sent /> : " + responseString);
See also: TcpListener.AcceptTcpClient | Socket Return to top Method: AcceptTcpClient() Summary Accepts a pending connection request C# Syntax: public TcpClient AcceptTcpClient(); Return Value: A TcpClient used to send and receive data. Exceptions Exception Type Condition InvalidOperationException The listener has not been started with a call to TcpListener.Start. Remarks TcpListener.AcceptTcpClient returns a TcpClient that you can use to send and receive data. Use TcpClient.GetStream to obtain the underlying NetworkStream of the TcpClient. NetworkStream inherits from Stream, which provides a rich collection of methods and properties for network communications. Note When you are through with the returned TcpClient, be sure to call it's TcpClient.Close method. Note If you want greater flexibility than a TcpClient offers, consider using TcpListener.AcceptSocket. Example In the following example, TcpListener.AcceptTcpClient is used to return a TcpClient. This TcpClient is used to communicate with the newly connected client.
// Accepts the pending client connection and returns a socket for communciation.
Socket socket = tcpListener.AcceptSocket();
Console.WriteLine("Connection accepted.");
string responseString = "You have successfully connected to me";
//Forms and sends a response string to the connected client.
Byte[] sendBytes = Encoding.ASCII.GetBytes(responseString);
int i = socket.Send(sendBytes);
Console.WriteLine("Message Sent /> : " + responseString);
See also: TcpClient | TcpListener.AcceptSocket Return to top Method: Equals( object obj ) Inherited See base class member description: System.Object.Equals C# Syntax: public virtual bool Equals( object obj ); For more information on members inherited from System.Object click on the link above. Return to top Overridden Method: Finalize() Summary Frees resources used by the TcpClient class. C# Syntax: ~TcpListener(); Remarks The finalizer for the TcpListener class calls the TcpListener.Stop method to free the underlying Socket. Return to top Method: GetHashCode() Inherited See base class member description: System.Object.GetHashCode C# Syntax: public virtual int GetHashCode(); For more information on members inherited from System.Object click on the link above. Return to top Method: GetType() Inherited See base class member description: System.Object.GetType C# Syntax: public Type GetType(); For more information on members inherited from System.Object click on the link above. Return to top Method: MemberwiseClone() Inherited See base class member description: System.Object.MemberwiseClone C# Syntax: protected object MemberwiseClone(); For more information on members inherited from System.Object click on the link above. Return to top Method: Pending() Summary Determines if there are pending connection requests. C# Syntax: public bool Pending(); Return Value: true if connections are pending; otherwise, false. Exceptions Exception Type Condition InvalidOperationException The listener has not been started with a call to TcpListener.Start. Remarks TcpListener.Pending polls for the underlying Socket to determine if there are pending connections. See also: TcpListener.Start Return to top Method: Start() Summary Starts listening to network requests. C# Syntax: public void Start(); Exceptions Exception Type Condition SocketException An error occurs while opening the network socket. Remarks TcpListener.Start initializes the underlying Socket. After this initialization, TcpListener.Start does the following: Binds the underlying Socket using the underlying IPEndPoint. Begins listening for client connections by calling the Socket.Listen method of the underlying Socket. This method only listens for connection requests. To detect these requests, you can use one of the following: The TcpListener.Pending method to detect incoming connection requests The TcpListener.AcceptSocket method or the TcpListener.AcceptTcpClient method to block until a connection request arrives. Example The following example demonstrates how TcpListener.Start is used to listen for incoming client connection attempts.
const int portNumber = 13;
TcpListener tcpListener = new TcpListener(portNumber);
tcpListener.Start();
Console.WriteLine("Waiting for a connection....");
try{
//Accept the pending client connection and return a TcpClient initialized for communication.
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
NetworkStream networkStream = tcpClient.GetStream();
string responseString = "You have successfully connected to me";
Byte[] sendBytes = Encoding.ASCII.GetBytes(responseString);
networkStream.Write(sendBytes, 0, sendBytes.Length);
Console.WriteLine("Message Sent /> : " + responseString);
//Any communication with the remote client using the TcpClient can go here.
//
////////
//Close TcpListener and TcpClient.
tcpClient.Close();
tcpListener.Stop();
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
See also: Socket.Listen | Socket.Bind | TcpListener.AcceptTcpClient | TcpListener.AcceptSocket | TcpListener.Pending Return to top Method: Stop() Summary Closes the listener. C# Syntax: public void Stop(); Exceptions Exception Type Condition SocketException An error occurs while closing the network socket. Remarks TcpListener.Stop closes the listener. Example The following example demonstrates using TcpListener.Stop to close the underlying Socket.
const int portNumber = 13;
TcpListener tcpListener = new TcpListener(portNumber);
tcpListener.Start();
Console.WriteLine("Waiting for a connection....");
try{
//Accept the pending client connection and return a TcpClient initialized for communication.
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
NetworkStream networkStream = tcpClient.GetStream();
string responseString = "You have successfully connected to me";
Byte[] sendBytes = Encoding.ASCII.GetBytes(responseString);
networkStream.Write(sendBytes, 0, sendBytes.Length);
Console.WriteLine("Message Sent /> : " + responseString);
//Any communication with the remote client using the TcpClient can go here.
//
////////
//Close TcpListener and TcpClient.
tcpClient.Close();
tcpListener.Stop();
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
See also: Socket.Close Return to top Method: ToString() Inherited See base class member description: System.Object.ToString C# Syntax: public virtual string ToString(); For more information on members inherited from System.Object click on the link above. Return to top Top of page Copyright (c) 2002 Microsoft Corporation. All rights reserved.