为什么我的TCP应用程序在快速发送时会丢失一些数据包

时间:2014-01-15 22:15:25

标签: c# sockets tcp

我正在使用异步套接字在C#中为每个服务器应用程序编写多个客户端。连接上的每个客户端发送10个项目。问题是,当快速启动大量客户端时,似乎每个客户端发送的项目少于10个,有时它不发送任何内容,服务器只记录它们的连接。

数据包结构是前4个字节是一个int,其中包含数据大小。这是服务器代码的一部分。每个连接的客户端都有自己的接收缓冲区,BeginReceive应该写入。

private void Recieve(IAsyncResult iar) //Called when socket receives something.
{
    Socket server_conn = (Socket)iar.AsyncState;

    if (!SocketConnected(server_conn))
    {
        server_conn.Close();
        logthis("Client Disconnected");
        return;
    }
    int n = server_conn.EndReceive(iar);  //Stop Receiving and parse data, n is number of bytes received

    ClientData asdf = null;
    foreach (ClientData cls in clientlist)
    {
        if (server_conn.RemoteEndPoint == cls.clientsock.RemoteEndPoint) //Who sent this data
        {
            asdf = cls; //cls is who sent this data

            //Start a new thread and pass received bytes to it in order to be parsed
            var t = new Thread(() => parse(cls, n,cls.recvbuffer));
            t.Start();
            Thread.Sleep(100);
            break;
        }
    }

    asdf.recvbuffer = new byte[1024];      //Clear buffer of client
    server_conn.BeginReceive(asdf.recvbuffer, 0, asdf.recvbuffer.Length, SocketFlags.None, new AsyncCallback(Recieve), server_conn); //Start receiving again

}

private void parse(ClientData theclient, int nobytesreceived, byte[] bytesreceived)
{
    ClientData cls = theclient;
    int n = nobytesreceived;
    byte[] receivedbytes = bytesreceived;


    lock(s)
    {
    if (!cls.dataphase)  //If there's no fragmented packets still waiting to be read
    {
        cls.dataphase = true;   
        byte[] sizeinbytes = new byte[4];
        for (int i = 0; i < 4; i++)
        {
            sizeinbytes[i] = receivedbytes[i];
        }
        int size = BitConverter.ToInt32(sizeinbytes, 0);  //Read first four bytes of packet to get size of data

        if ((n - 4) == size)  //If received number of bytes - 4 is equals to datasize
        {
            byte[] payload = new byte[size];
            Array.Copy(receivedbytes, 4, payload, 0, (n - 4)); //Copy data to separately to payload array to be displayed to user
            logthis(cls.clientsock.RemoteEndPoint.ToString());
            logthis(Encoding.ASCII.GetString(payload));
            cls.dataphase = false;       //packet read successfully 
        }
        else if ((n - 4) < size) //If received amount of bytes is less than data size (fragmented data)
        {
            cls.data = new byte[size];
            for (int i = 4; i <= n - 4; i++)
            {
                cls.data[i - 4] += receivedbytes[i];
            }

            cls.datasize = size; //And cls.dataphase will remain true so it can be handled correctly the next time we receive something from same client
        }
        else if((n-4) > size)  //If received amount of bytes is bigger than data (lumped packets)
        {
            byte[] payload = new byte[size];
            byte[] otherpacket = new byte[(n - 4) - size];

            for(int i = 0; i < size; i++)
            {
                payload[i] += receivedbytes[i + 4];

            }

            logthis(cls.clientsock.RemoteEndPoint.ToString());
            logthis(Encoding.ASCII.GetString(payload));
            Array.Copy(receivedbytes, (size + 4), otherpacket, 0, ((n - 4) - size));
            receivedbytes = new byte[(n - 4) - size];
            receivedbytes = otherpacket;
            cls.dataphase = false;
            parse(cls, ((n - 4) - size), receivedbytes); //Send rest of packet to read again
        }

    }
    else
    {
        //not implemented, supposed to handle fragmented packets
        if (n >= cls.datasize)
        {

        }
        else if (n < cls.datasize)
        {

        }

    }

}

}

1 个答案:

答案 0 :(得分:3)

您的问题来自

else
{
    //not implemented, supposed to handle fragmented packets

我会把钱放在你正在发表其他声明并丢失数据的事实上。一旦你没有完整读取一个数据包或者从你的读取函数返回的两个数据包(这比你想象的要常见得多),你的客户端现在卡在cls.dataphase = true;中,永远不会得到出来的。