TCPClient.我如何接收重大信息

本文关键字:信息 何接收 TCPClient | 更新日期: 2023-09-27 18:27:31

我有以下代码:

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。在调试器中,CCD_ 1等于CCD_。

TCPClient.我如何接收重大信息

您调用流。循环阅读,直到阅读完整条信息。如果你提前知道消息大小,这相对容易:

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个字节中),您应该先阅读这些内容,然后按照我的建议进行操作。