daniel
daniel

Reputation: 35683

TCP packets lost

I transfer a video stream from one c# app to another. When I set the frame rate high I don't get the right data after some time.

//Receiver
Socket s;
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
var ip = IPAddress.Any;
myList = new TcpListener(ipAd, 8001);
myList.Start();
s = myList.AcceptSocket();

while (runThread)
{
        int buffertype = -1; MemoryStream img = null; int size = 0; int 
        pos = 0;
        try
        {
            // length of frame
            byte[] lengthb = new byte[32];
            int k = s.Receive(lengthb, SocketFlags.None);
            size = BitConverter.ToInt32(lengthb, 0);
            pos = 0;

            byte[] lengthframe = new byte[size];
            // chunking of data
            int chunksize = 100;
            while (pos < size - chunksize)
            {
                int rec = s.Receive(lengthframe, pos, chunksize, SocketFlags.None);
                pos += rec;
            }
            s.Receive(lengthframe, pos, size - pos, SocketFlags.None);

            img = new MemoryStream(lengthframe);
        }
 }

 // Other app: Sender (all is send)
 MemoryStream ms = new MemoryStream();
 img.CopyTo(ms);                
 byte[] ba = ms.ToArray();
 var buffer = BitConverter.GetBytes(ba.Length);
 stm.Write(buffer, 0, buffer.Length);
 stm.Write(ba, 0, ba.Length);

How can I be safe that all packages are received?

Upvotes: 1

Views: 61

Answers (1)

Andriy Tylychko
Andriy Tylychko

Reputation: 16256

sender:

stm.Write(buffer, 0, buffer.Length);

receiver:

byte[] lengthb = new byte[32];
int k = s.Receive(lengthb, SocketFlags.None);

are you sure buffer.Length type is 32 bytes long (256 bits)? I suppose it's rather 4 or 8 bytes long. So you're potentially receiving 32 bytes buffer which includes your length field in the beggining and the rest is a part of your encoded video stream. Then you throw away that part. Doesn't sound good.

Upvotes: 2

Related Questions