C# socket sends first 2 bytes correctly and the rest are null bytes

Viewed 30

I have a problem with a socket server receiving first 2 bytes from the client correctly and the rest are just null bytes, and the packet length is correct as well,

Client send function:

internal void Send(byte[] _data) {
        if (!IsValid()) return;
        try {
            ushort wrLenBuf = (ushort)_data.Length;
            byte[] data = new byte[2 + wrLenBuf];
            BinaryPrimitives.WriteUInt16LittleEndian(data, wrLenBuf);
            xMemUtils.MemCopy2(_data, 0, ref data, 2);

            string s = "";
            foreach (var b in _data) s += b + " ";
            Console.WriteLine(s);

            stream.WriteAsync(data, 0, wrLenBuf + 2);
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
            Close();
        }
    }

Which produces the output: 2 4 8 48 48 48 48 48 48 48 48 48 48 48 48 which is the correct bytes of 15 length.

The server ReceivePacket function:

        int totBytesRead;
        private async void RcvPkt(ushort pktSz) {
            Console.WriteLine("PktSz: " + pktSz);
            totBytesRead = 0;
            byte[] buf = new byte[pktSz];
            while (totBytesRead < pktSz) {
                readLen = await stream.ReadAsync(buf.AsMemory(totBytesRead, pktSz - totBytesRead));
                if (readLen == 0) {
                    Close();
                    return;
                }
                totBytesRead += readLen;
                Console.WriteLine("TotalBytesRead: " + totBytesRead);
            }
            string s = "RcvArr: ";
            foreach (var b in buf) s += b + " ";
            Console.WriteLine(s);
            //Console.WriteLine("PSz: " + pktSz + " BfLen: " + buf.Length + " | " + Encoding.UTF8.GetString(buf, 0, pktSz));
            //Packet.Handler.thiz.Handle(this, buf);
            RcvPktSz();
        }

Output:

PktSz: 15
TotalBytesRead: 15
RcvArr: 2 4 0 0 0 0 0 0 0 0 0 0 0 0 0

I tried with this 15byte length array, 41byte length array, both receive full packet but only the first 2 bytes correctly and the rest are null bytes \0.

That's from client to server, on the other hand when sending a string from the server to client it gets it correctly.

I would appreciate anyone helping or having any idea of what's goin wrong here.

0 Answers
Related