当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - sending data over networkstream goes wrong

问题描述:

I have the following code that sends data:

writer is a NetworkStreamWriter instance.

img is an Image instance.

writer.AutoFlush = true;

writer.WriteLine("picture");

BinaryWriter bWriter = new BinaryWriter(writer.BaseStream);

MemoryStream ms = new MemoryStream();

img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

byte[] buffer = new byte[ms.Length];

ms.Seek(0, SeekOrigin.Begin);

ms.Read(buffer, 0, buffer.Length);

bWriter.Write(buffer.Length);

bWriter.Write(buffer);

bWriter.Flush();

ms.Flush();

then, on the client side, I have a receiving code:

var reader = new StreamReader(stream);

string message = await reader.ReadLineAsync();

BinaryReader breader = new BinaryReader(stream);

int ctBytes = breader.ReadInt32();

MemoryStream ms = new MemoryStream(breader.ReadBytes(ctBytes));

Image img = Image.FromStream(ms);

Bitmap bmp = new Bitmap(img, (int)System.Windows.SystemParameters.PrimaryScreenWidth, (int)System.Windows.SystemParameters.PrimaryScreenHeight);

ShowImage(bmp);

ms.Flush();

breader.BaseStream.Flush();

the sending code runs every 40 miliseconds, and the receiving code runs inside a loop asynchronously (works when the "picture" string is sent)

but the receiving code works only for about 4 iterations, afterwards the ctBytes becomes negative and an exception is being throwed (you can't read a negative number of bytes).

I don't know what is wrong.

分享给朋友:
您可能感兴趣的文章:
随机阅读: