Recently I started using Socket and faced the problem of data transfer, that is, if I send byte [] with a volume of more than 100 kb. it gives me an error when disassembling a document

Error = "There is an error in XML document (13, 2970)." Message: "The following elements are not closed: _Message, MainData, DataMessages. Line 13, position 2970."

ReceiveSocket = Listen.AcceptSocket(); if (!Form1.ValueSendMessages.OffGetMessage) { Byte[] Receive = new Byte[256]; using (MemoryStream _Message = new MemoryStream()) { Int32 ReceivedBytes; do { ReceivedBytes = ReceiveSocket.Receive(Receive, Receive.Length, SocketFlags.None); _Message.Write(Receive, 0, ReceivedBytes); } while (ReceiveSocket.Available > 0); using (StringReader ReconvertString = new StringReader(Encoding.Default.GetString(_Message.ToArray()))) { XmlSerializer XmlData = new XmlSerializer(typeof(DataMessages)); DataMessages GetDataContract = (DataMessages)XmlData.Deserialize(ReconvertString); 

Here is the error

 DataMessages GetDataContract = (DataMessages)XmlData.Deserialize(ReconvertString); 

But the most interesting thing is that when I perform transitions in this code through a debugger, the problem disappears, it never happened again, it seems that he does not have time to transmit all the data on variables at once.

If after ReceiveSocket = Listen.AcceptSocket (); install Thread.Sleep (2000); then everything works, what could be the problem

    1 answer 1

    The problem is that reading from a socket does not guarantee delivery of the entire message at a time. If you know the length of the message being sent, read until you have received all the bytes of the message. If you do not know, build a communication protocol so that the size is transmitted first.

    The loop on ReceiveSocket.Available incorrect: you can select data faster than they arrive, and the data does not appear in the socket until the sending party completes sending (or the intermediate server does not pass). At this point, you are already exiting the reading cycle.