-
streamReader problems
Been a long time sence I last posted here, got alot better at C# than I used to be.
I am creating a simple server and client program. The client connects to the server (both running on my computer) and that works fine, they can connect without errors.
And as far as I can tell I can send data using a networkstream and laying a streamreader and/or streamwriter over it.
But when I go to read a line of data the program freezes or acts as if it is constantly trying to do somthing (like writing a 1gb file). I waited for a couple mins to see if I could grab an exception but none came, it just sat there frozen.
writing code:
Code:
if (host == false)
{
clientwriter.Write(textBox_TextWrite.Text);
clientwriter.Flush();
}
else
{
serverwriter.Write(textBox_TextWrite.Text);
clientwriter.Flush();
}
reading code:
Code:
if (host == false)
{
textBox_TextRead.Text = clientreader.ReadToEnd();
}
else
{
try
{
textBox_TextRead.Text = serverreader.ReadLine();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
if you need more code just ask.
-
Step through it with a breakpoint in your debugger (see below). I have a feeling your code is blocking on the clientreader.ReadToEnd(); line - are you sure data is being sent?
Using the debugger
Assuming you're using Visual Studio, press F9 to set a breakpoint on a line of code, then run the program with F5. When it hits your line of code, the program will freeze and return to Visual Studio with that line highlighted. Press F11 to step through the code line by line to see what its doing.
-
Ok I see how to use the debugger but it doesn't say anything is wrong.
-
I changed the code a bit
writing:
Code:
if (host == false)
{
clientwriter.Write(textBox_TextWrite.Text);
clientwriter.Flush();
}
if (host == true)
{
serverwriter.Write(textBox_TextWrite.Text);
serverwriter.Flush();
}
reading:
Code:
if (host == false)
{
if (clientreader.EndOfStream == false)
{
textBox_TextRead.Text = clientreader.ReadLine();
}
}
if (host == true)
{
textBox_TextRead.Text = serverreader.ReadLine();
}
But now I know it just stops when it gets to the clientreader.ReadLine(); line. Found that out using the debugger now that I know how to use it :D
-
Yep, the debugger will save you a lot of time :) If it's pausing on ReadLine(), that probably means it's waiting until it reaches the end of the line. Try changing it to Read(), or ensure a '\n' or '\r\n' (preferably use Environment.NewLine) is sent at the end of the text.
-
ahh yah I looked at my book more closely and found I should use writeline instead of write.
That fixed it, thanks. This is the first time tcp/ip worked for me.