TCPClient. How do I receive big messages?

2019-09-16 00:55发布

I have the following code:

private string Connect()
{
    string responseData;

    try
    {
        TcpClient client = new TcpClient(ServerIp, Port);
        client.ReceiveBufferSize = Int32.MaxValue;

        Byte[] data = Encoding.GetEncoding(1251).GetBytes(ReadyQuery);


        NetworkStream stream = client.GetStream();

        // send data
        stream.Write(data, 0, data.Length);


        // buffer
        data = new Byte[65536];               

        Int32 bytes = stream.Read(data, 0, data.Length);
        responseData = Encoding.GetEncoding(1251).GetString(data, 0, bytes);                

        // close all
        stream.Close();
        client.Close();
        return responseData;
    }

I have problem with a big message. The receive message size is 22K chars. I get only part of message.
How can I receive big messages?

PS. In the debugger bytes equal 4096.

1条回答
孤傲高冷的网名
2楼-- · 2019-09-16 01:30

You call stream.Read in a loop until you read the entire message. If you know the message size in advance it's relatively easy:

int messageSize = 22000;
int readSoFar = 0;
byte [] msg = new byte[messageSize];

while(readSoFar < messageSize)
{
    var read = stream.Read(msg, readSoFar, msg.Length - readSoFar);
    readSoFar += read;
    if(read==0)
        break;   // connection was broken
}

If the message size is part of the message (say, encoded in the first 4 bytes), you should read those first and then do as I suggested.

查看更多
登录 后发表回答