的TcpClient。我如何收到大消息?

时间:2012-03-13 09:01:51

标签: c# .net tcp tcpclient

我有以下代码:

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;
    }

我有一个大消息的问题。接收消息大小为22K字符。我只收到部分信息 我怎样才能收到大消息?

PS。在调试器中bytes等于4096

1 个答案:

答案 0 :(得分:4)

您在循环中调用stream.Read,直到您阅读整个消息。如果您事先知道邮件大小,则相对容易:

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
}

如果邮件大小是邮件的一部分(例如,在前4个字节中编码),则应首先阅读这些邮件,然后按照我的建议进行操作。