orbit orbit - 16 days ago 5
C# Question

C# Stream read in a constant loop

Using c#, I would like to make a loop where it repeats the task only after the function before completes. Here's my code

TcpListener serv = new TcpListener(IPAddress.Any, 19148);
serv.Start();
TcpClient clie = serv.AcceptTcpClient();
NetworkStream stre = clie.GetStream();
byte[] buffer = new byte[2048];
Form1 f1 = new Form1();
f1.Show();
f1.TopMost = true;
///the code to repeat starts here
stre.Write(Encoding.UTF8.GetBytes("Enter Message: "), 0, Encoding.UTF8.GetByteCount("Enter Message: "));
stre.Read(buffer, 0, buffer.Length);
f1.label1.Text = Encoding.UTF8.GetString(buffer);
///ends here


I have read up on loops but every time I use one it crashes my program.

I have tried most things, but the most promising one so far has been this but it only shows the form on the last input.

int i = 0;
while(i < 3)
{
stre.Write(Encoding.UTF8.GetBytes("Enter Message: "), 0, Encoding.UTF8.GetByteCount("Enter Message: "));
stre.Read(buffer, 0, buffer.Length);
f1.label1.Text = Encoding.UTF8.GetString(buffer);
i++;
}


Any help would be appreciated as I have no leads to even point me in the right direction.

Answer

You really need to move the read to it's own thread (or use Async methods). You called .Show on the form, but the actual show isn't instantaneous, and it needs the thread you are using for your input to be able to draw itself. If you absolutely can't move your read loop to another thread (Async, BackgroundWorker, Task, etc), you could change your code to the following:

TcpListener serv = new TcpListener(IPAddress.Any, 19148);
serv.Start();
TcpClient clie = serv.AcceptTcpClient();
NetworkStream stre = clie.GetStream();
byte[] buffer = new byte[2048];
Form1 f1 = new Form1();
f1.Show();
f1.Refresh(); // Do it RIGHT NOW!
f1.TopMost = true;
int i = 0;
while(i < 3)
{
    stre.Write(Encoding.UTF8.GetBytes("Enter Message: "), 0, Encoding.UTF8.GetByteCount("Enter Message: "));
    stre.Read(buffer, 0, buffer.Length);
    f1.label1.Text = Encoding.UTF8.GetString(buffer);
    f1.label1.Refresh(); // Do it right now!
    i++;
}

You will find that your form will display, but it is absolutely frozen. You can't resize it, it won't repaint itself until your loop finishes. Not a very good experience.

Comments