다음은 내가 사용하는 방법입니다. 나는이 코드에 새로운 것은 없다고 믿는다.Stream.Read가받은 데이터를 반환하지 않습니다.
public static byte[] ReadFully(Stream stream, int initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 1K.
if (initialLength < 1)
{
initialLength = 1024;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}
// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
내 목표는 TCP 클라이언트에서 보낸 데이터를 읽는 것입니다. box{"id":1,"aid":1}
내 응용 프로그램에서 Jason과 같은 텍스트로 해석하는 명령입니다. 그리고이 텍스트는 매번 같은 크기 일 필요는 없습니다. 다음에 run{"id":1,"aid":1,"opt":1}
이 올 수 있습니다.
이 줄에서 호출하는 메서드. 우리는 스트림에서 데이터를 볼 수 있지만
var serializedMessageBytes = ReadFully(_receiveMemoryStream, 1024);
Please click to see; Received data in receiveMemoryStream 의 ReadFully
방법 는 "chunck"항상 0
를 반환 및 방법은 {byte[0]}
를 반환합니다.
도움을 주신 모든 분들께 진심으로 감사드립니다.
왜'stream.CopyTo (memoryStream)'과'memoryStream.ToArray()'를 사용하지 않으시겠습니까? –
버퍼 때문에? –
후드에서 스트림 기본 버퍼 크기는'DefaultCopyBufferSize = 81920;' –