TCP客户端.如何接收大消息? [英] TCPClient. How do I receive big messages?

查看:33
本文介绍了TCP客户端.如何接收大消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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 个字符.我只收到部分消息.
如何接收大消息?

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?

附注.在调试器中 bytes 等于 4096.

PS. In the debugger bytes equal 4096.

推荐答案

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

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
}

如果消息大小是消息的一部分(例如,以前 4 个字节进行编码),您应该先阅读这些内容,然后按照我的建议进行操作.

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.

这篇关于TCP客户端.如何接收大消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆