How to get the server response efficiently?

1

I'm creating a Client / Server application It works as a chat so the server can send messages to the client and vise versa.

To send messages I use an event

private void btnsend_Click(object sender, EventArgs e)
{
            enviar();
 }

It means that when I click the button it executes this function that sends the message to the server.

To receive messages from the server I thought of using timer or similar; I tried first with a while this way;

private void btnsend_Click(object sender, EventArgs e)
    {
                enviar();
                While(true)
               {
                 Receber();
               }

     }

But I soon realized that it would be infinite and I would not be able to use it anymore so I thought about the timer.

Another attempt was to do the following

private void btnsend_Click(object sender, EventArgs e)
        {
            enviar();
        }


        public  void enviar()
        {

            StreamWriter writer = new StreamWriter(ntcpClient.GetStream());
            writer.AutoFlush = true;
            writer.WriteLine(gettime() + ":" + txtmsgsend.Text );
            this.txtmsg.Text += gettime() +":" + txtmsgsend.Text + "\n";
            txtmsgsend.Text = "";
            if (txtmsgsend.Text == "/clear")
            {
                txtmsg.Text = "";
            }
            receber();
        }

But there is a problem just checking if I got a message if I sent a message and it still does not solve the problem.

Full Code

    
asked by anonymous 02.09.2017 / 00:56

1 answer

0

The most correct way to do this is not so, but I believe it will work too:

public Servidor()
{
    InitializeComponent();
    receber();
}

public void receber()
{
    Task f = Task.Factory.StartNew(() =>
    {
        while (true)
        {
            StreamReader reader = new StreamReader(ntcpClient.GetStream());
            this.txtmsg.Text += gettime() + ":" + reader.ReadLine() + "\n";
            Thread.Sleep(50);
        }
    });
}

What the code does is let you execute it infinitely, asynchronously.

    
02.09.2017 / 01:53