15.4 Creating a Stream-Based Client

 <  Day Day Up  >  

You want to create a stream-based client to communicate with a server using a specified protocol.


Technique

To connect to a server using TCP, create a TcpClient object and call the Connect method, passing the remote server's IP address and port number as parameters into the method. The method will return, but you are not guaranteed that the connection has been made. In Listing 15.5, the Connect method is contained within a try block that will catch an error if the connection attempt fails.

Listing 15.5 Connecting to a Remote Server
 [STAThread] static void Main(string[] args) {     TcpClient client = new TcpClient();     Byte[] read = new Byte[1024];     string gameServer = "";     if (args.Length != 1)     {         gameServer = "127.0.0.1";     }     else     {         gameServer = args[0];     }     // Verify that the server exists     IPHostEntry serverIP = Dns.Resolve( gameServer );     if( serverIP == null )     {         Console.WriteLine("Cannot find server: {0}", gameServer);         return;     }     else     {         Console.WriteLine( "Found server. {0}", serverIP.HostName );     }     // Try to connect to the game server on port 2003     try     {         client.Connect(gameServer, 2003);     }     catch (SocketException e)     {         Console.WriteLine("Cannot connect to {0}: {1}",           gameServer, e.Message);         return;     } 

Once you successfully make a connection using the Connect method, you are ready to begin communicating with the server. Create a new Stream object and assign it using the return value of the GetStream method defined in the TcpClient class. You will use this Stream object to both send and receive data to the server. The Read and Write methods of the Stream class both accept a byte array, an offset to where you want the method to read or write to in the array, and the total number of bytes to read or write. If you recall, these are the same methods employed when reading from a file stream, and the code is similar to the server-based code in Listing 15.2 for the Socket object.

Listing 15.6 is the remaining client portion of the number-guessing game server shown in Recipe 15.1, "Creating a Stream-Based Server." The main communication loop occurs in the StartGame method and uses the same protocol defined in that section. The code for this method is available for download on this book's Web site at http://www.samspublishing.com.

Listing 15.6 Communicating with a Remote Server
 // Get the stream     Stream s;     try     {         s = client.GetStream();     }     catch (InvalidOperationException exc)     {         Console.WriteLine("Cannot connect to {0}: {1}", gameServer, exc.Message);         return;     }     Console.WriteLine( "Connected to game server" );     string response = GetResponse(s);     Console.WriteLine( "Response\r\n--------\r\nCode: {0} Message: {1} ",         GetResponseCode(response), GetResponseData(response));     // connected begin game     StartGame( s );     client.Close();     // Wait for user response to exit     Console.WriteLine("Press Return to exit");     Console.Read();     client.Close(); } 

Comments

This recipe and Recipe 15.1 complete the necessary pieces to create a server and a client that can connect using a protocol that was designed to play a number-guessing game. Utilizing other protocols such as HTTP, FTP, and NNTP follows a similar pattern of commands being sent to a server, which in turn returns the requested information. The code uses numerical status messages and commands, which is consistent with other protocols, to alleviate any issues such as case consistency.

Creating a client for a specific server is similar to creating the actual server itself. In fact, a lot of the objects that are in use are mirrored on both ends. For instance, a TcpListener class is used to listen for incoming connections on a server, and a TcpClient is used to make those connections. Furthermore, the server uses a Socket object and its associated Send and Receive methods to stream data back to the client, and the client utilizes a Stream object and the methods Read and Write , whose parameters are almost identical to the Send and Receive Socket methods.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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