Receiving data in TCP

前端 未结 10 1258
借酒劲吻你
借酒劲吻你 2020-12-18 04:59

If i send 1000 bytes in TCP, does it guarantee that the receiver will get the entire 1000 bytes \"togther\"? or perhaps he will first only get 500 bytes, and later he\'ll re

10条回答
  •  醉话见心
    2020-12-18 05:52

    You decide, in your message that how many bytes your message shall contain. For instance in your case its 1000. Following is up and running C# code to achieve the same. The method returns with 1000 bytes. The abort code is 0 bytes; you can tailor that according to your needs.

    Usage:

    strMsg = ReadData(thisTcpClient.Client, 1000, out bDisconnected);
    

    Following is the method:

        string ReadData(Socket sckClient, int nBytesToRead, out bool bShouldDisconnect)
        {
            bShouldDisconnect = false;
    
            byte[] byteBuffer = new byte[nBytesToRead];
            Array.Clear(byteBuffer, 0, byteBuffer.Length);
    
            int nDataRead = 0;
            int nStartIndex = 0;
    
            while (nDataRead < nBytesToRead)
            {
    
                int nBytesRead = sckClient.Receive(byteBuffer, nStartIndex, nBytesToRead - nStartIndex, SocketFlags.None);
    
                if (0 == nBytesRead)
                {
                    bShouldDisconnect = true;
                    //0 bytes received; assuming disconnect signal
                    break;
                }
    
                nDataRead += nBytesRead;
                nStartIndex += nBytesRead;
            }
    
            return Encoding.Default.GetString(byteBuffer, 0, nDataRead);
        }
    

    Let us know this didn't help you (0: Good luck.

提交回复
热议问题