Tcpclient provides client connection for TCP network services.
System. Object
System. net. sockets. tcpclient
[C#]public class TcpClient : IDisposable
Remarks
TcpclientClass provides some simple methods for connecting, sending, and receiving streaming data through the network in synchronous blocking mode.
To enableTcpclientConnect and exchange data, use TCPProtocoltypeCreatedTcplistenerOrSocketYou must listen for incoming connection requests. You can use either of the following two methods to connect to the listener:
- CreateTcpclientAnd call one of the three available connect methods.
- Create by using the host name and port number of the remote hostTcpclient. This constructor will automatically try a connection.
Note:Use the udpclient class to send connectionless data packets in synchronous blocking mode.
Description of successors:To send and receive data, useGetstreamMethod to obtainNetworkstream. CallNetworkstreamOfWriteAndReadMethod to send and receive data between the remote host. UseCloseMethod release andTcpclientAll associated resources.
Example C # The following example creates
TcpclientConnection.
Static void connect (string server, string message)
{
Try
{
// Create a tcpclient.
// Note, for this client to work you need to have a tcpserver
// Connected to the same address as specified by the server, Port
// Combination.
Int32 Port = 13000;
Tcpclient client = new tcpclient (server, Port );
// Translate the passed message into ASCII and store it as a byte array.
Byte [] DATA = system. Text. encoding. ASCII. getbytes (Message );
// Get a client stream for reading and writing.
// Stream = client. getstream ();
Networkstream stream = client. getstream ();
// Send the message to the connected tcpserver.
Stream. Write (data, 0, Data. Length );
Console. writeline ("sent: {0}", message );
// Receive the tcpserver. response.
// Buffer to store the response bytes.
Data = new byte [2, 256];
// String to store the response ASCII representation.
String responsedata = string. empty;
// Read the first batch of the tcpserver response bytes.
Int32 bytes = stream. Read (data, 0, Data. Length );
Responsedata = system. Text. encoding. ASCII. getstring (data, 0, bytes );
Console. writeline ("Received: {0}", responsedata );
// Close everything.
Client. Close ();
}
Catch (argumentnullexception E)
{
Console. writeline ("argumentnullexception: {0}", e );
}
Catch (socketexception E)
{
Console. writeline ("socketexception: {0}", e );
}
Console. writeline ("\ n press enter to continue ...");
Console. Read ();
}