我想创建一个通过网络流式传输多个图像的项目。我只是想从小的,功能性的代码开始,但我已经遇到了一个时髦的问题。收到图像,但它包含图形错误,就像它只是它的一部分。
可悲的是,无法显示图像低的原因,这里是链接。 http://img543.imageshack.us/img543/1508/buggedy.jpg当然,百万美元的回答。 ^^
TcpListener listener;
TcpClient client;
TcpClient datatoclient;
NetworkStream stream;
主持人部分:
listener = new TcpListener(5000);
listener.Start();
datatoclient = listener.AcceptTcpClient();
NetworkStream nowystream = datatoclient.GetStream();
MemoryStream ms = new MemoryStream();
byte[] image = File.ReadAllBytes("default.jpg");
switch (trackBar1.Value)
{
case 0:
image = File.ReadAllBytes("mirrion.jpg");
break;
case 1:
image = File.ReadAllBytes("tenis.jpg");
break;
case 2:
image = File.ReadAllBytes("marisasold.jpg");
break;
}
// get the image size in bytes
int numberOfBytes = image.Length;
// put the size into an array
byte[] numberOfBytesArray = BitConverter.GetBytes(numberOfBytes);
// send the image size
nowystream.Write(numberOfBytesArray, 0, numberOfBytesArray.Length);
// send the image
nowystream.Write(image, 0, numberOfBytes);
客户端部分:
client = new TcpClient("127.0.0.1", 5000);
stream = client.GetStream();
byte[] data = new byte[4];
// read the size
stream.Read(data, 0, data.Length);
int size = BitConverter.ToInt32(data, 0);
label1.Text = size.ToString();
// prepare buffer
data = new byte[size];
// load image
stream.Read(data, 0, data.Length);
// save image to file for test
File.WriteAllBytes("received.jpg", data);
MemoryStream MS = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(MS);
答案 0 :(得分:3)
stream.Read
不保证它会读取data.Length
个字节。相反,它返回读取的字节数。因此,您应检查其返回值并继续读取,直到获得所有字节。
请参阅http://msdn.microsoft.com/en-us/library/system.io.stream.read(v=vs.90).aspx(第Return Value
部分)
读取方法可以是这样的
void Read(Stream stream, byte[] buffer,int offset,int len)
{
int read = 0;
while (read < len)
{
read += stream.Read(buffer, offset + read, len-read);
}
}