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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With