TCPClient. How do I receive big messages?

我的梦境 提交于 2019-12-12 02:48:16

问题


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:


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.



来源:https://stackoverflow.com/questions/9680962/tcpclient-how-do-i-receive-big-messages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!