UWP c# read XML from StreamSocket
I'm trying to communicate with an XMPP (Jabber) server via a TCP network socket ( StreamSocket
) and I'm using the following code to read what the server has send to me:
StreamSocket tcpSocket;
StreamReader reader;
int BUFFER_SIZE = 4096;
// Connecting to a remote XMPP server ....
reader = new StreamReader(tcpSocket.InputStream.AsStreamForRead());
string result;
while (true)
{
result = "";
while (true)
{
char[] buffer = new char[BUFFER_SIZE];
await reader.ReadAsync(buffer, 0, BUFFER_SIZE);
string data = new string(buffer);
// Detecting if all elements in the buffer array got replaced => there is more to read
if (data.IndexOf(" ") >= 0 || reader.EndOfStream)
{
result + data.Substring(0, data.IndexOf(" "));
break;
}
result += data;
}
Debug.WriteLine(result);
}
My Code works just fine for strings with a length < 4096 chars, but as soon as the string gets longer than 4096 chars it fails (won't detect the message end). It waits until it receives a new string < 4096 chars, concatenates both strings and returns them as one string.
Is there a way to get the actual length of a string and read them successively?
You have set 4096 to the BUFFER_SIZE
and it is be set to the count parameter in StreamReader.ReadAsync
and the char Array. When the string contain more than 4096 chars, it will fails.
You should be able to get the actual length in the Stream, we can use Stream.Length
to get the length of the stream in bytes. The last char of Array is "