0

i have an issue where im not receiving any bytes from the connected TcpClient!

Server: (i attempt to add the received message into a listbox, but nothing comes out.

   //tl is a TcpListener
   //I set this up in a 500 milisecond loop. No worries about that.
   if (tl.Pending())
   {
     TcpClient tcp = tl.AcceptTcpClient();
     var s = tcp.GetStream();
     int bytesRead = s.Read(new byte[tcp.ReceiveBufferSize], 0, 
     tcp.ReceiveBufferSize);
     string dataReceived = Encoding.ASCII.GetString(new 
     byte[tcp.ReceiveBufferSize], 0, bytesRead);
     listBox1.Items.Add(dataReceived);
     tcp.Close();
     oac++; //Overall connection count
     label3.Text = "Overall Connections: " + oac; //logging connections
   }

Client:

 void Send(){
    TcpClient c = new TcpClient(Im not including my ip., 4444);
    System.IO.StreamWriter w = new System.IO.StreamWriter(c.GetStream());
    byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes($"Username: \"
    {textBox1.Text}\" | Password: \"{textBox2.Text}\"");
    NetworkStream nwStream = c.GetStream();
    nwStream.Write(bytesToSend, 0, bytesToSend.Length);
    nwStream.Flush();
  }

I The connection works, but theres some issues receiving data. it just comes out blank

  • You create your dataReceived string using byte array (new byte[...]) filled with 0, so it is always empty. And you read data from socket to another byte array which is immediately discarded – Evk Nov 07 '17 at 20:41

1 Answers1

0

On serverside, your problem is that you renew toy byte array new byte[tcp.ReceiveBufferSize]. You could also do something like this:

using( var inputStream = new MemoryStream() )
{
  tcp.GetStream().CopyTo(inputStream);
  Encoding.ASCII.GetString(inputStream.ToArray());
  listBox1.Items.Add(dataReceived);
  ...
}

Remember using on all IDisposable's, else you will run out of resources.

Frank Nielsen
  • 1,546
  • 1
  • 10
  • 17