Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TcpClient send/close problem

Tags:

c#

tcp

sockets

send

Do I need to close the connection to have messages actually sent? Because whether I use send command or use a network stream, my messages don't get processed until I close connection. Is that the way it's supposed to be or am I missing something?

Ok here's the code.

private void connectButton_Click(object sender, EventArgs e)
{
   try
   {
      client = new TcpClient();
      client.Connect(ip, port);
      netStream = client.GetStream();
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.Message);
   }
}

private void disconnectButton_Click(object sender, EventArgs e)
{
   if (client != null)
   {
      if (client.Connected)
      {
         client.Close();
         client = null;
      }
   }
}

private void sendButton_Click(object sender, EventArgs e)
{
   byte[] cmd = ToByteArray("bla bla bla");
   netStream.Write(cmd, 0, cmd.Length);
   netStream.Flush();
}

I don't think it has to do with this method but have a look.

public static byte[] ToByteArray(string str)
{
   System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
   return encoding.GetBytes(str);
}
like image 789
joshua Avatar asked Jul 01 '26 23:07

joshua


1 Answers

you are probably using buffered streams, try to call the .Flush method, which is also automatically called when clode is invoked.

like image 185
Davide Piras Avatar answered Jul 04 '26 14:07

Davide Piras