I have a TCP connection between two computers using windows forms. I have an array of integers which I am serializing using the XmlSerializer class and sending it using the StreamWriter and receiving using StreamReader.
Sending:
NetworkStream stream = m_client.GetStream(); //m_client is a TCPclient
StreamWriter m_writer = new StreamWriter(stream);
int[] a = new int[3] { 10,20,30 };
XmlSerializer serializer = new XmlSerializer(typeof(int[]));
serializer.Serialize(m_writer, a);
//m_writer.Flush(); //Doesn't help
//m_writer.Close();
On the receiving end:
TcpClient client = (TcpClient)p_client;
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
if (stream.CanRead)
{
XmlSerializer serializer = new XmlSerializer(typeof(int[]));
int[] numbers = (int[])serializer.Deserialize(reader);
MessageBox.Show(numbers[0].ToString()); //Is not reached
MessageBox.Show(numbers[1].ToString());
MessageBox.Show(numbers[2].ToString());
}
The problem is that the reader on the receiver does not stop reading unless I terminate the connection or close the m_writer on the senders end (in which case I can't use it for sending again). And if it doesn't stop reading, the next line (namely, MessageBox.Show(numbers[0].ToString())) will not work.
I need suggestions on how I can inform the receiver to stop reading after 30 or how can it understand when to stop reading?
Edit:
I got the XMLserializer idea from How to send integer array over a TCP connection in c#
I found an answer which requires terminating the connection, which I'd rather not do unless it is the only way possible. XmlSerializer Won't Deserialize over NetworkStream