I'm trying to pass a custom class
from one tcp client to another (using TcpListener
, TcpClient
and XmlSerializer
).
I got 1 problem that breaks into 2 problems.
when i'm using this code, the client hangs while Serilization is being done (i think the other side doesnt know when the data is fully sent):
public void SendData(myMessage messageClass)
{
NetworkStream serverStream = tcpServer.GetStream();
XmlSerializer xmlSrlz = new XmlSerializer(typeof(myMessage));
xmlSrlz.Serialize(serverStream, messageClass);
serverStream.Flush();
}
public myMessage ReadData()
{
while (true)
{
NetworkStream clientStream = client.GetStream();
XmlSerializer xmlSrlz = new XmlSerializer(typeof(myMessage));
int bytesToread;
byte[] inStream = new byte[10025];
myMessage msg;
do
{
msg = (myMessage)xmlSrlz.Deserialize(clientStream);
clientStream.Flush();
}
while (((bytesToread = clientStream.Read(inStream, 0, (int)client.ReceiveBufferSize)) > 0));
return msg;
}
}
So, when i searched around i noticed i can dispose the stream (or use using
) and that way let the other side know that the Data has fully sent and theres no more Data to send:
public void SendData(myMessage messageClass)
{
using (NetworkStream serverStream = tcpServer.GetStream())
{
XmlSerializer xmlSrlz = new XmlSerializer(typeof(myMessage));
xmlSrlz.Serialize(serverStream, messageClass);
serverStream.Flush();
}
}
public myMessage ReadData()
{
while (true)
{
using (NetworkStream clientStream = client.GetStream())
{
XmlSerializer xmlSrlz = new XmlSerializer(typeof(myMessage));
int bytesToread;
byte[] inStream = new byte[10025];
myMessage msg;
do
{
msg = (myMessage)xmlSrlz.Deserialize(clientStream);
clientStream.Flush();
}
while (((bytesToread = clientStream.Read(inStream, 0, (int)client.ReceiveBufferSize)) > 0));
return msg;
}
}
}
But now i lost the connection of them 2 clients.
when i'm trying to send another Message i get the exception:
The operation is not allowed on non-connected sockets.
So how can i send the Serilized object without breaking the connection?