从NetworkStream读取的正确方法是什么?

时间:2018-12-22 13:52:20

标签: c# server networkstream

我正在开发一种软​​件,该软件将不断接收各种类型和不同长度的请求。

尤其是length是令我感兴趣的部分,因为我不知道要去接收的消息的长度。

此刻,我编写了这段代码,该代码将接收到的字节写成非常大的byte[],然后在第二byte[]中仅复制数据的长度。

//get the network stream
NetworkStream networkStream = tcpClient.GetStream();

//initialize an bytes array of size 5 MB
byte[] largeArray = new byte[5242880];

//write the bytes in the largeArray
//determines the length of the received message
int lenght = networkStream.Read(largeArray, 0, largeArray.Length);

//initialize an bytes array with the correct message length
byte[] messageArray = new byte[lenght];

//make a copy from the largeArray to the messageArray with the right lenght
Buffer.BlockCopy(largeArray, 0, messageArray, 0, messageArray.Length);

我想知道这种方法是否可以纠正,或者有更好的替代方法来接收未知长度的消息吗?

0 个答案:

没有答案
相关问题