I am using TcpClient and NetworkStream to initiate a connection to a POP server for authentication. Bad practice, good for learning.
When I Telnet into the POP server, the response produced is initially :
+OK Dovecot Ready
User enters username
+OK
User enters pass which is checked
+OK if valid -N if not
My program is connecting to the POP server, opening a StreamReader and Writer, writing all of this data and checking the response.
using (TcpClient client = new TcpClient("host.university.ie", 110)) {
using (NetworkStream stream = client.GetStream()) {
using (StreamReader reader = new StreamReader(stream)) {
using (StreamWriter writer = new StreamWriter(stream)) {
string response = reader.ReadLine();
writer.Write("USER " + username );
response = reader.ReadLine();
writer.Write("PASS " + password );
string response = reader.ReadLine();
Response.Write(@"<script language='javascript'>alert('The following response as been received: \n" + response + " .');</script>");
isValid = response[ 0 ].Equals('+');
writer.WriteLine("quit\n");
}
}
}
}
}
However, when I enter this code, the query goes into an infinite loop. The confusing thing is that when I reduce the number of calls to reader.ReadLine() to one, it returns “+OK Dovecot Ready”! So it is connecting to the POP server but it will not work after this. Does anyone have any ideas what might be causing this?
No, it isn’t an infinite loop. The second call to
reader.ReadLine()will never return, because you haven’t finished sending theUSERcommand to the server. You must send linefeed characters using.WriteLineinstead of.WriteTry this:
and this:
EDIT: Added calls to
.Flushas per spender‘s suggestion.