I'm trying to get a synchronous connection to a server using the various .NET stream classes. It seems that I can send a command to the server successfully, but nothing is returned (or the StreamReader returns before the data can be read off of the socket). Here's the psuedocode/real code :
static void Main(string[] args)
{
string newsServerName = "msnews.microsoft.com";
int newsServerPort = 119;
TcpClient newsServer;
try {
newsServer = new TcpClient();
newsServer.Connect( newsServerName, newsServerPort );
}
catch( SocketException e )
{
string error = "Failed to connect to " + newsServerName + " on port " + newsServerPort;
Console.WriteLine( error );
Console.WriteLine( e.Message );
return;
}
NetworkStream netStream;
StreamReader reader;
StreamWriter writer;
try {
netStream = newsServer.GetStream();
reader = new StreamReader( netStream );
writer = new StreamWriter( netStream );
// Flush the read buffer if there's anything in there from the Connect.
if ( reader.Peek() > -1 ) {
while ( reader.Peek() > -1 ) {
Console.WriteLine( reader.ReadLine() );
}
}
string sendMessage = "LIST" + "\\r\\n";
Console.WriteLine( "Sending message." );
writer.WriteLine( sendMessage );
writer.Flush();
Console.WriteLine( "Waiting for response." );
while ( reader.Peek() > -1 ){
Console.WriteLine( reader.ReadLine() );
}
}
catch( Exception e ) {
Console.WriteLine( "Error talking with server." );
Console.WriteLine( e.Message );
}
}
The last while loop never writes anything out. At the very least I should get the response from the server. How can I make the StreamReader wait until there is data before trying to dump out? I know this can be done with plain Send and Recv on a Socket, but I would like to use the Stream* classes if possible. greg