Title: NetStream
Focus point: Read, Write
Body:
int size = Read (buf, 0, buf.length);
Here will read the length of bytes, if less than this amount, the back is garbage data, I was confused by this, looked at two geniuses to find the problem, I read directly into the BUF, and then through Encoding.Default.GetString (BUF) to get the string, Results half a day did not find the problem, the output display also normal (...) ), in fact the length of the string is buf.length, only when the length of the string is removed only to find the exception! The return value of read represents the number of data actually read, which can then be called Encoding.Default.GetString (buf, 0, size), and the correct string is obtained.
Now the new problem arises, if the other side of the write data is greater than this value, the latter will be stopped in the buffer, waiting for the next receive, it is likely that there will be a problem (a one-time resolution, especially at the beginning of the case with control characters). So we can judge if size = = Buf.length, then continue to receive, and then multiple received results are grouped together. However, the data sent by the exact size of the buf.length error, so the two sides can stipulate that if the data sent is an integer multiple of buf.length, then add "#END" and then send, and the receiver received a separate #end will also indicate a read-in end.
1 classMynetstream2 {3 Public Const intMAX =5;4 NetworkStream stream;5 PublicMynetstream (NetworkStream stream)6 {7 This. Stream =stream;8 }9 Public stringRead ()Ten { One stringRET =""; A byte[] buf =New byte[MAX]; - intsize; - Do the { -size = stream. Read (BUF,0, buf. Length); - strings = Encoding.Default.GetString (buf,0, size); -Console.Write (S +"size ="+size); + if(!s.equals ("#END")) ret + =s; - Else Break; +} while(Size = =MAX); A returnret; at } - Public voidWrite (strings) - { - byte[] buf =Encoding.Default.GetBytes (s); - if(BUF. Length% MAX = =0) - { inBUF = Encoding.Default.GetBytes (S +"#END"); - } toStream. Write (BUF,0, buf. Length); + } -}
C # NetStream