Recipe 13.10 Writing a TCP Client

Problem

You want to interact with a TCP-based server.

Solution

Use the TcpClient class to connect to and converse with a TCP-based server by passing the address and port of the server to talk to. This example will talk to the server from Recipe 13.9:

 public string RunClient(string address,int port) {     string response = "";     // Set up a listener on that address/port     TcpClient tcpClient = new TcpClient(address,port);     if(tcpClient != null)     {         string message = "Hello there";         // Translate the passed message into UTF8ASCII and store it as a Byte array.         byte[] bytes = Encoding.ASCII.GetBytes(message);                  NetworkStream stream = tcpClient.GetStream( );         // Send the message to the connected TcpServer.          // The write flushes the stream automatically here         stream.Write(bytes, 0, bytes.Length);         // Get the response from the server         StreamReader reader = new StreamReader(stream,Encoding.UTF8);         try         {             response = reader.ReadToEnd( );         }         finally         {             // Close the reader             reader.Close( );         }         // Close the client         tcpClient.Close( );     }     // Return the response text     return response; } 

Discussion

RunClient is designed to send one message containing "Hello World" to the server, get the response and return it as a string, then terminate. To accomplish this, it creates the TcpClient on the address and port passed in, and then it gets the bytes for the string using the Encoding.UTF8.GetBytes method. Once it has the bytes to send, it gets the NetworkStream from the TcpClient by calling the GetStream method and sends the message using the Write method.

In order to receive the response from the server, the blocking ReadToEnd method is then called. Once ReadToEnd returns, the string contains the response.

See Also

See the "TcpClient Class," "NetworkStream Class," and "Encoding.ASCII Property" topics in the MSDN documentation.



C# Cookbook
C# 3.0 Cookbook
ISBN: 059651610X
EAN: 2147483647
Year: 2003
Pages: 315

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net