Question

I wanted to create a project for streaming multiple images through net. I just wanted to start with small, functional code but already encountered a funky problem for me. Image is received, but it contains graphical bugs like its only a part of it.

Sadly cant show images cause of low rputation, here is link. http://img543.imageshack.us/img543/1508/buggedy.jpg

Of course, million dollars for answer. ^^

TcpListener listener;
TcpClient client;
TcpClient datatoclient;
NetworkStream stream;

Host part:

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 part:

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);
Was it helpful?

Solution

stream.Read doesn't guarantee that it will read data.Length bytes. Instead it returns number of bytes read. So you should check its return value and continue reading till you get all the bytes.

See http://msdn.microsoft.com/en-us/library/system.io.stream.read(v=vs.90).aspx (Section Return Value)

Thr read method can be something like this

void Read(Stream stream, byte[] buffer,int offset,int len)
{
    int read = 0;
    while (read < len)
    {
        read += stream.Read(buffer, offset + read, len-read);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top