0

我想创建一个通过网络传输多个图像的项目。我只是想从小的功能性代码开始,但对我来说已经遇到了一个时髦的问题。图像已收到,但它包含图形错误,例如它的一部分。

可悲的是无法显示图像导致低信誉,这里是链接。 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);
4

1 回答 1

3

stream.Read不保证它会读取data.Length字节。相反,它返回读取的字节数。所以你应该检查它的返回值并继续阅读,直到你得到所有的字节。

请参阅http://msdn.microsoft.com/en-us/library/system.io.stream.read (v=vs.90).aspx(部分Return Value

Thr 读取方法可以是这样的

void Read(Stream stream, byte[] buffer,int offset,int len)
{
    int read = 0;
    while (read < len)
    {
        read += stream.Read(buffer, offset + read, len-read);
    }
}
于 2013-04-04T17:07:49.567 回答