How to get the server response efficiently?

Asked

Viewed 70 times

1

I am creating a Client/Server application Acts 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 runs this Function that sends the message to the server.

To receive the messages from the server I thought to use timer or also similar; I tried first with a while this way;

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

     }

But then I realized it would be infinite and I couldn’t use the send 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’s a problem I just check if I got a message if I send a message which still doesn’t solve the problem.

Entire code

  • The issue of while(1) just do it asynchronously, take a look at the namespace System.Threading.Task. But don’t do this within an event, create a void method and call it in Load().

  • It is possible, but it is not the solution, it will consume processing or will have to wait for the right time, it would be better to create an architecture that is waiting for a message.

  • Some example is that I didn’t really understand

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.