Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte[256] over TCP limiting to 5 characters

Tags:

c#

.net

tcpclient

I am having an issue with a TCP server\client I am writing in .NET 3.5 (C#).

Whenever I transfer data using the code below, only 5 characters transfer to the server. How can I fix my code so that I have more than 5 characters transferring?

TcpClient client = new TcpClient(connectto.ToString(), portto);
Stream s = client.GetStream();
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);

Byte[] data = new Byte[256];
data = System.Text.Encoding.ASCII.GetBytes("auth:" + adminPASS.Text);

s.Write(data, 0, data.Length);

data = new Byte[256];

String responseData = String.Empty;

Int32 bytes = s.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);

The server is only getting the first 5 characters of whatever is transferred. The rest is lost.

like image 717
foxbot Avatar asked Oct 01 '22 07:10

foxbot


1 Answers

Stream.Read can return fewer bytes than requested, so you need to call it in a loop until EOF is reached, like this:

int bytes;
int offset = 0;

while ((bytes = s.Read(data, offset, data.Length - offset) != 0)
{
   offset += bytes;
}

Also, you never Dispose() your streams, so it's likely that they aren't getting flushed. Use a using statement around all your IDisposable objects.

like image 58
dan04 Avatar answered Oct 11 '22 20:10

dan04